How to convert number such as 24 to the two words "two", "four".
-
2show what you've got so far, and explain what is/isn't working about it. – user2366842 Sep 11 '13 at 18:17
-
Have you tried putting a CASE statement inside an InStr loop? – Johnny Bones Sep 11 '13 at 18:19
-
2@JohnnyBones: trolling the newbies isn't nice. – Wooble Sep 11 '13 at 18:20
-
Have a look at: http://stackoverflow.com/questions/18737863/passing-a-function-to-re-sub-in-python – Jon Clements Sep 11 '13 at 18:23
-
@Wooble - OK, so I reverted to VBA. But it only took a second to find http://stackoverflow.com/questions/11479816/what-is-the-python-equivalent-for-a-case-switch-statement and http://stackoverflow.com/questions/663171/is-there-a-way-to-substring-a-string-in-python, which (combined) should answer his question. – Johnny Bones Sep 11 '13 at 18:24
-
possible duplicate of [How do I tell Python to convert integers into words](http://stackoverflow.com/questions/8982163/how-do-i-tell-python-to-convert-integers-into-words) – Robᵩ Sep 11 '13 at 18:38
1 Answers
Quick way I thought of. First you need a way to loop through the integer. You can try doing some weird diving by 10 and using the modulus of it... or just convert it to a string.
Then you can iterate through each 'number' in the string and use a simple lookup table to print out each number.
numberconverterlookup={'1':'one'
'2':'two'
'3':'three'
'4':'four'
'5':'five'
'6':'six'
'7':'seven'
'8':'eight'
'9':'nine'
'0':'zero'
}
number = 24
stringnumber = str(number)
for eachdigit in stringnumber:
print numberconverterlookup[eachdigit]
Note this only handles single digits and can't easily handle large numbers. Otherwise you'd have to write out each number in the lookup table by hand. That is very cumbersome.
Some key concepts are illustrated here:
Dictionary: This maps a 'key' to a 'value'. I.e. '1' maps to 'one'
For loop: This allows us to go through each digit in the number. In the case of 24, it will loop twice, once with eachdigit set to '2', and loops around again with eachdigit set to '4'. We cant loop through an integer because it is itself a single entity.
Typecasting: This converts the integer type 24 into a string '24'. A string is basically a list of individual characters grouped together, whereas an integer is a single entity.

- 799
- 6
- 10
-
To expand on gregb's answer, you could use a lookup table for digits and a table for each place, ie ones, tens, hundreds, thousands, etc. This allows you to expand easily while still accounting for specially termed numbers. For example, 14 is "fourteen", not ten four, even though 24 is twenty-four and 94 is ninety-four. – Chris Arena Sep 11 '13 at 18:27