有沒有辦法在不丟失前導零的情況下將字符串中的數字,或者int變成單詞?我試圖將日期和時間和電話號碼轉換爲單詞,但第二次我將字符串值轉換爲int,我失去了我的前導零。如何在保持前導零的同時將數字轉換爲單詞?
這裏是我的代碼,現在可以對單詞進行編號,只要沒有前導零,它就可以很好地工作。這裏是我的問題的一個例子... 比方說,我打開一個日期08-02-2004我不想輸出爲零八個零二...等 但我要做到這一點在它的當前狀態我不得不圍繞一些方法來做...除非我失去了一些東西。
units = ["", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine "]
teens = ["", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
tens = ["", "ten", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety"]
thousands = ["","thousand", "million", "billion", "trillion",
"quadrillion", "quintillion", "sextillion", "septillion", "octillion",
"nonillion", "decillion", "undecillion", "duodecillion", "tredecillion",
"quattuordecillion", "sexdecillion", "septendecillion", "octodecillion",
"novemdecillion", "vigintillion "]
def numToWords(self, num):
words = []
if num == 0:
words.append("zero")
else:
numStr = "%d" % num
numStrLen = len(numStr)
groups = (numStrLen + 2)/3
numStr = numStr.zfill(groups * 3)
for i in range(0, groups*3, 3):
h = int(numStr[i])
t = int(numStr[i+1])
u = int(numStr[i+2])
g = groups - (i/3 + 1)
if h >= 1:
words.append(units[h])
words.append("hundred")
if t > 1:
words.append(tens[t])
if u >= 1:
words.append(units[u])
elif t == 1:
if u >= 1:
words.append(teens[u])
else:
words.append(tens[t])
else:
if u >= 1:
words.append(units[u])
if g >= 1 and (h + t + u) > 0:
words.append(thousands[g])
return ' '.join([w for w in words])
任何幫助或建議,將不勝感激。
你想要多少個前導零? –