dictionary - How to convert numbers into strings in python? 1 -> 'one' -


if want program let user input number (e.g. 1, 13, 4354) how can print (one, thirteen, 4 3 5 four) make sense? if it's 2 digit, print though it's joined (thirty-one) if it's more 2 print them sepretly, 1 same line joined space, tried dictionary, , think it's possible, can't figure out how it?

l = input('enter number: ')  if len(l) > 2:     nums = {'1':'one',             '2':'two',             '3':'three',             '4':'four',             '5':'five',             '6':'six',             '7':'seven',             '8':'eight',             '9':'nine'} elif len(l) == 2:     tens = {'10'}   k, v in nums.items():     print(k, v) 

this wrong code, finished result this? in advance!

to access items dictionary, can dictionary[key]. value returned.

let's input "8".

you can print nums[l] (inside conditional statement), , return "eight".


also, it's better if create dictionaries outside of conditional structures prevent nameerrors , can access both dictionaries anywhere.


if have input "324", can use combination of str.join() , list comprehension:

l = "324" nums = {'1':'one',         '2':'two',         '3':'three',         '4':'four',         '5':'five',         '6':'six',         '7':'seven',         '8':'eight',         '9':'nine'}  print ' '.join(nums[i] in l) 

explanation:

[nums[i] in l] same as:

returned_list = [] number in l:     returned_list.append(d[number]) 

str.join() joins every item in list together, separated space. ' '.join(['one', 'two', 'three']) returns 'one 2 three'


Comments

Popular posts from this blog

java - activate/deactivate sonar maven plugin by profile? -

python - TypeError: can only concatenate tuple (not "float") to tuple -

java - What is the difference between String. and String.this. ? -