使get number函数更具pythonic

时间:2019-05-07 09:24:09

标签: python algorithm

我有波纹管类型的字符串:

str = 'PE01-A1'
str2 = 'PE01-A/1'
str3 = 'PE01-A01'

我还编写了一个获取波纹管编号的函数,可以:

def get_latter_number(str):
    total = len(str)
    if total == 0:
        return str

    number = None
    for i in range(total):
        tmp_str = str[(total-i - 1): total]
        try:
            number = int(tmp_str)
        except Exception as e:
            break

    return number


num = get_latter_number(str)
print(num)  # there will be 1

我的方法有效,但是我认为它不是pythonic的,谁能告诉我如何编写更简洁的函数?

1 个答案:

答案 0 :(得分:0)

这可以做到:

def get_latter_number(str):
    for i in range(len(str)):
        try:
            return int(str[i: ])
        except:
            pass
    return None