我只是將此代碼轉換爲一個整數(儘管我實際上並未使用整數)到一個字符串。例如,45 - >四十五。它完美的工作,但代碼很長。有什麼方法可以縮短它嗎?將2位數字轉換爲python中的字符串
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.")
我很抱歉,我不能設法通常張貼問題。 – Faradrim
你可以將每個數字映射到相應的單詞上。 –
你可以適應這個更一般的基於Java的解決方案:https://stackoverflow.com/a/3299672/684776 – mac9416