How to convert an integer number to words in python?
Use modules for it:
https://pypi.python.org/pypi/num2words
Also, check similar questions: How do I tell Python to convert integers into words
You can install the modules and see how it is implemented there.
But your problem is solved like:
def numbers_to_words (number):
number2word = {'1': "one", '2': "two", '3': "three", '4': "four", '5': "five", '6': "six",
'7': "seven", '8': "eight", '9': "nine", '0': "zero"}
return " ".join(map(lambda i: number2word[i], str(number)))
print(numbers_to_words(1234))
How to convert numbers to words without using num2word library?
Your first statement logic is incorrect. Unless Number
is 1 or smaller, that statement is always True; 200 is greater than 1 as well.
Use and
instead, and include 1
in the acceptable values:
if (Number >= 1) and (Number <= 19):
You could use chaining as well:
if 1 <= Number <= 19:
For numbers of 20 or larger, use divmod()
to get both the number of tens and the remainder:
tens, remainder = divmod(Number, 10)
Demo:
>>> divmod(42, 10)
(4, 2)
then use those values to build your number from the parts:
return num2words2[tens - 2] + '-' + num2words1[below_ten]
Don't forget to account for cases when the number is above 20 and doesn't have a remainder from the divmod operation:
return num2words2[tens - 2] + '-' + num2words1[remainder] if remainder else num2words2[tens - 2]
All put together:
def number(Number):
if 0 <= Number <= 19:
return num2words1[Number]
elif 20 <= Number <= 99:
tens, remainder = divmod(Number, 10)
return num2words2[tens - 2] + '-' + num2words1[remainder] if remainder else num2words2[tens - 2]
else:
print('Number out of implemented range of numbers.')
Related Topics
Pandas Groupby Columns With Nan (Missing) Values
Python Converting MySQL Query Result to Json
Python - Ensuring a Variable Holds a Positive Number
Reading a CSV That Sometimes Contain Multiple Whitespaces
How to Set Proxy for Chrome in Python Webdriver
Pandas Get the Age from a Date (Example: Date of Birth)
How to Calculate Rolling/Moving Average Using Python + Numpy/Scipy
Why Does the Session Cookie Work When Serving from a Domain But Not When Using an Ip
Centering Text in Ipython Notebook Markdown/Heading Cells
Converting a Numpy Array into a Dict of Values Mapped to Rows
Django - How to Retrieve Data in Database in Dropdownlist
Blender - How to Add a Color to an Object