从字符串中读取Python中的Number

时间:2018-02-27 13:46:30

标签: python string function numbers

我刚刚从字符串中读取数字时遇到问题。我不知何故没有得到适当的价值。我需要区分1到2个编号的字符串并需要考虑它。我的输出如下所示:

9
1

但它应该是:

9
10
def StringToNumber(Period):
    if Period[-1:] == "D":
        period_unit = int(Period[:1])
    elif Period[-1:] == 'M':
        period_unit = int(Period[:1])
    elif Period[-1:] == 'W':
        period_unit = int(Period[:1])
    elif Period[-1:] == 'Y':
        period_unit = int(Period[:1])
    elif Period == '':
        period_unit = int(0)
    else:
        raise Exception('Problems')
    return period_unit

years_string1 = '9Y'
years_string2 = '10Y'

years_number1 = StringToNumber(years_string1)
years_number2 = StringToNumber(years_string2)

print(years_number1)
print(years_number2)

3 个答案:

答案 0 :(得分:1)

如果year_string的格式相同,为什么不这样做?

def StringToNumber(Period):
    period_unit = Period[:-1]
    return period_unit

years_string1 = '9Y'
years_string2 = '10Y'

years_number1 = StringToNumber(years_string1)
years_number2 = StringToNumber(years_string2)

print(years_number1)
print(years_number2)

答案 1 :(得分:0)

这可能会有所帮助。要获取最后一个元素,请使用 [ - 1] 而不是[-1:]。要排除最后一个元素,请使用 [: - 1] 而不是[:1]

def StringToNumber(Period):
    if Period[-1] == "D":
        period_unit = int(Period[:-1])
    elif Period[-1] == 'M':
        period_unit = int(Period[:-1])
    elif Period[-1] == 'W':
        period_unit = int(Period[:-1])
    elif Period[-1] == 'Y':
        period_unit = int(Period[:-1])
    elif Period == '':
        period_unit = int(0)
    else:
        raise Exception('Problems')
    return period_unit

years_string1 = '9Y'
years_string2 = '10Y'

print(StringToNumber(years_string1))
print(StringToNumber(years_string2))

<强>输出:

9
10

答案 2 :(得分:0)

您需要使用-1代替1

试试这个:

intervals = ['D', 'M', 'W', 'Y']
def StringToNumber(Period):

    if Period[-1:] in intervals:
        period_unit = int(Period[:-1])
    elif Period == '':
        period_unit = int(0)
    else:
        raise Exception('Problems')
    return period_unit

years_string1 = '9Y'
years_string2 = '10Y'

years_number1 = StringToNumber(years_string1)
years_number2 = StringToNumber(years_string2)

print(years_number1)
print(years_number2)

这使您的代码更好,并减少冗余