将整数转换为英语有序字符串的最pythonic方法?

时间:2018-10-20 18:46:26

标签: python python-3.x

我对Python比较陌生(主动编码2个月),我刚刚编写了一个简单的函数,该函数将整数转换为字符串,并添加英语2字符字符串作为后缀,该后缀通常表示整数的顺序。一个列表。 我很快就编写出了行之有效的代码,但这是杀死我,因为我知道,还有一种更Python的方式可以做到这一点。

所以我想要实现的是:

i_to_suffix_str(1) => '1st'
i_to_suffix_str(11) => '11th'
i_to_suffix_str(33) => '33rd'
i_to_suffix_str(142) => '142nd'

...等等。

我的代码(既简洁又不带Python语言):

def i_to_suffix_str(i):
    sig_digits = i % 100
    if sig_digits > 3 and sig_digits < 21:
        suffix = 'th'
    elif (sig_digits % 10) == 1:
        suffix = 'st'
    elif (sig_digits % 10) == 2:
        suffix = 'nd'
    elif (sig_digits % 10) == 3:
        suffix = 'rd'
    else:
        suffix = 'th'
    return str(i) + suffix

我已经尝过了Python的方式,而且我知道必须有更好的方式。 ...任何参与者?

2 个答案:

答案 0 :(得分:0)

也许使用字典对其进行修整

lst = [1, 11, 20, 33, 44, 50, 142]
sigs = {1: 'st', 2: 'nd', 3: 'rd'}
for i in lst:
    if 3 < i < 21:
        print(f'{i}th')
    elif int(str(i)[-1]) in sigs.keys():
        print(f'{i}{sigs[int(str(i)[-1])]}')
    else:
        print(f'{i}th')
# 1st 11th 20th 33rd 44th 50th 142nd

答案 1 :(得分:0)

您可以将字典与Python ternary operator结合使用,例如:

def i_to_suffix_str(i):
    sig_digits = i % 100
    suffixes = {1: 'st', 2: 'nd', 3: 'rd'}
    suffix = 'th' if 3 < sig_digits < 21 else suffixes.get(sig_digits % 10, 'th')
    return str(i) + suffix

print(i_to_suffix_str(1))
print(i_to_suffix_str(11))
print(i_to_suffix_str(33))
print(i_to_suffix_str(142))

输出

1st
11th
33rd
142nd
相关问题