有没有办法将数字,字符串中的ether或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])
对此的任何帮助或建议将不胜感激。
答案 0 :(得分:1)
确保首先提供字符串,并在必要时仅将其评估为int。 E.g:
def numToWords(self, numStr):
words = []
if int(numStr) == 0:
words.append("zero")
else:
# no longer needed, it's already a string
# numStr = "%d" % num
numStrLen = len(numStr)
groups = (numStrLen + 2) /
...
答案 1 :(得分:1)
使用%d将int格式化为字符串时,会删除任何前导零。要保留它们,您需要指定最小位数,如下所示:
numStr = "%03d" % num
这会将前导零附加到任何小于3位的数字(在这种情况下,最小位数为3)。但是,在你肆无忌惮地使用前导零之前,首先需要确定你想要看多少位数。
答案 2 :(得分:0)
使用递归方法的解决方案怎么样?
def numToWords(i):
if i < 20:
result = 'zero,one,two,three,four,five,six,\
seven,eight,nine,ten,eleven,twelve,\
thirteen,fourteen,fifteen,sixteen,\
seventeen,eighteen,nineteen'.split(',')[i]
elif i < 100:
result = ',,twenty,thirty,forty,fifty,sixty,seventy,\
eighty,ninety'.split(',')[i//10]
if i % 10:
result += ' ' + numToWords(i % 10)
elif i < 1000:
result = checkio(i // 100) + ' hundred'
if i % 100:
result += ' ' + numToWords(i % 100)
return result