0

Possible Duplicate:
How do I tell Python to convert integers into words

I'm trying to write a simple function that takes an input as an integer, and then displays it as the word. I'm not sure how to word this problem correctly. This is for a clock app, and this is what I'm doing, but I'm sure there is an easier way out there.

if h == 1: h = "One"
if h == 2: h = "Two"
if h == 3: h = "Three"
if h == 4: h = "Four"
if h == 5: h = "Five"
if h == 6: h = "Six"
if h == 7: h = "Seven"
if h == 8: h = "Eight"
if h == 9: h = "Nine"
if h == 10: h = "Ten"
if h == 11: h = "Eleven"
if h == 12: h = "Twelve"

Can someone show me an easier way to do this.

Community
  • 1
  • 1
user1692517
  • 1,122
  • 4
  • 14
  • 28

4 Answers4

5
hours = ["Twelve", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven"]

for i in range(0, 24):
    print(hours[i % 12])

You can do it this way, or use a dictionary where each hour's "name" is indexed by the number it represents.

Borgleader
  • 15,826
  • 5
  • 46
  • 62
3

Use zip to build a dictionary, and look up the words with digits:

hour_word = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", 
"Eight", "Nine", "Ten", "Eleven", "Twelve"]
clock_dict = dict(zip(range(1, 13), hour_word))
clock_dict[1]
# 'One'
clock_dict[2]
# 'Two'
clock_dict[12]
# 'Twelve'
K Z
  • 29,661
  • 8
  • 73
  • 78
1

Easy way,

h = ['zero','one','two','three','four','five','six'][h] # check bounds first

IF you don't have a zero, leave it in there, or make it None,It'll still work.

Just more pythonic this way. and support arbitary values

lst = ['zero','one','two','three','four','five','six']
d = dict(zip(range(len(lst)),lst))
print (d[2]) #prints two
st0le
  • 33,375
  • 8
  • 89
  • 89
0

Here's a relatively compact and pretty version of code that will do what you want in the general sense (for all numbers, not just up to twelve).

level1 = [ "", "one", "two", "three", "four",  "five", "six", "seven", "eight", "nine" ]
level2 = [ "", "eleven", "twelve", "thirteen",  "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" ]
level3 = [ "", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" ]
level4 = [ "","thousand", "million" ]


def number2string(number):
    if number == 0:
        return "zero"
    string = ""
    nparts = (len(str(number)) + 2) / 3
    filled = str(number).zfill(nparts * 3)
    for i in range(nparts):
        d3, d2, d1 = map(int, filled[3*i:3*(i+1)])
        d4 = nparts - i - 1
        string += " "*(i>0)
        string += (d3>0)*(level1[d3] + " hundred" + " "*(d2*d1>0))
        if d2 > 1:
            string += level3[d2] + (" " + level1[d1])*(d1 >= 1)
        elif d2 == 1:
            string += level2[d1]*(d1 >= 1) or level3[d2]
        elif d1 >= 1:
            string += level1[d1]
        string += (" " + level4[d4])*(d4 >= 1 and (d1+d2+d3) > 0)
    return string
Karol
  • 1,246
  • 2
  • 13
  • 20