我刚刚将此代码转换为字符串转换整数(尽管我实际上并不使用整数)。例如,45 - >四十五。它工作得很好,但代码很长。有什么方法可以缩短它吗?
num = input("Enter a two digit number: ")
first_digit = num[0]
if first_digit == "2":
first_digit_str = "Twenty"
elif first_digit == "3":
first_digit_str = "Thirty"
elif first_digit == "4":
first_digit_str = "Forty"
elif first_digit == "5":
first_digit_str = "Fifty"
elif first_digit == "6":
first_digit_str = "Sixty"
elif first_digit == "7":
first_digit_str = "Seventy"
elif first_digit == "8":
first_digit_str = "Eighty"
elif first_digit == "9":
first_digit_str = "Ninety"
second_digit = num[1]
if second_digit == "1":
second_digit_str = "-One"
elif second_digit == "2":
second_digit_str = "-Two"
elif second_digit == "3":
second_digit_str = "-Three"
elif second_digit == "4":
second_digit_str = "-Four"
elif second_digit == "5":
second_digit_str = "-Five"
elif second_digit == "6":
second_digit_str = "-Six"
elif second_digit == "7":
second_digit_str = "-Seven"
elif second_digit == "8":
second_digit_str = "-Eight"
elif second_digit == "9":
second_digit_str = "-Nine"
if first_digit == "1":
if second_digit == "1":
print("Eleven")
elif second_digit == "2":
print("Twelve")
elif second_digit == "3":
print("Thirteen")
elif second_digit == "4":
print("Fourteen")
elif second_digit == "5":
print("Fifteen")
elif second_digit == "6":
print("Sixteen")
elif second_digit == "7":
print("Seventeen")
elif second_digit == "8":
print("Eighteen")
elif second_digit == "9":
print("Nineteen")
else:
print(first_digit_str + second_digit_str)
k = input("Press enter to close.")
答案 0 :(得分:0)
使用 n2w
库:
安装(从命令行):
pip install n2w
用法:
import n2w
num = 45
num_words = '-'.join(w.capitalize() for w in n2w.convert(num).split())
print(num_words)
输出:
Forty-Five
答案 1 :(得分:0)
答案 2 :(得分:0)
这有点短:
num_int = input("Enter a two digit number: ")
above_19 = { "2":"Twenty", "3":"Thirty", "4": "Forty", "5": "Fifty",
"6": "Sixty" , "7": "Seventy", "8": "Eighty", "9": "Ninety"}
above_10 = { "1":"Eleven", "2":"Twelve", "3":"Thirteen", "4":"Fourteen",
"5": "Fifteen" , "6": "Sixteen", "7":"Seventeen", "8":
"Eighteen", 9:"Nineteen"}
digit_2 = { "1": "-One", "2": "-Two", "3":"-Three", "4":"-Four",
"5": "-Five" , "6": "-Six", "7": "-Seven", "8":"-Eight",
"9": "-Nine"}
num = str(num_int)
first_digit = num[0]
second_digit = num[1]
if (first_digit == "1"):
result = above_10[second_digit]
else:
result = above_19[first_digit]+digit_2[second_digit]