【问题标题】:How to check for string and get the string before after checking如何检查字符串并在检查后获取字符串
【发布时间】:2021-11-01 17:12:44
【问题描述】:

如果我有一个字符串“3 apples”或“3apples”并进行如下检查:

fruit = "3 apples"

if fruit.find('apples') > -1:

如果陈述属实,我如何才能得到苹果前面的数字 3?

【问题讨论】:

    标签: python python-3.x string


    【解决方案1】:

    使用str.split (假设提供的字符串格式为:'int(s) apples''int(s)apples'

    fruit = "3 apples"
    
    try:
        num, word = fruit.split()
    except ValueError:
        num = ''.join(filter(str.isdigit, fruit))
        word = ''.join(filter(str.isalpha, fruit))
    
    if word == 'apples':
        print(num)
    

    使用re

    import re
    
    fruit = "3 apples"
    match = re.match(r"(\d+)\s*apples$", fruit)
    if match:
        print(match.group(1))
    

    【讨论】:

    • 如果字符串像“3apples”一样放在一起怎么办?
    • 那么正则表达式是您的最佳选择。我会编辑。
    • 使用(\d+)\s*apples$
    【解决方案2】:

    您可以遍历字符串并找到数字:

    fruit = "3 apples"
    
    if fruit.find('apples') > -1:
        print("".join([i for i in fruit if i.isdigit() ]))
    

    【讨论】:

    • 如果字符串是“12 个苹果”怎么办?
    • 不太可能,但是“2.5 个苹果”?
    猜你喜欢
    • 1970-01-01
    • 2015-08-26
    • 2023-03-25
    • 2015-01-15
    • 2014-03-03
    • 2011-02-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多