snippetpythonMajor
Create the English word for a number
Viewed 0 times
theenglishnumbercreatewordfor
Problem
I cobbled together a function from various sources that takes an integer and returns it as its respective English word formatted as a string. The function is as follows:
def int2word(num, separator="-"):
"""Transforms integers = 0:
words = twenty2ninety[tens] + separator + \
ones_and_teens[below_ten].lower()
else:
words = twenty2ninety[tens]
return words
elif 100 0:
words = ones_and_teens[hundreds] + separator + "hundred" + separator + twenty2ninety[
tens].lower() + separator + ones_and_teens[below_ten].lower()
else:
words = ones_and_teens[
hundreds] + separator + "hundred" + separator + ones_and_teens[below_ten].lower()
return words
else:
print("num out of range")Solution
There's an easier way.
We have the
The advantage of this module is that it supports multiple languages:
More, you can even generate ordinal numbers like forty-second.
A small python example for converting numbers to words using
You can read more about what you can do using this module here
NOTE: In case somebody is wondering why this is not a code review (such as comments on the posted code), is because in the unedited question the author specifically asked if there is already a library for this.
We have the
num2words module which can be easily installed via pip:pip install num2wordsThe advantage of this module is that it supports multiple languages:
- en (English, default)
- fr (French)
- de (German)
- es (Spanish)
- lt (Lithuanian)
- lv (Latvian)
- en_GB (British English)
- en_IN (Indian English)
- no (Norwegian)
- pl (Polish)
- ru (Russian)
- dk (Danish)
- pt_BR (Brazilian Portuguese)
More, you can even generate ordinal numbers like forty-second.
A small python example for converting numbers to words using
num2words looks like this:>>> from num2words import num2words
>>> num2words(42)
forty-two
>>> num2words(42, ordinal=True)
forty-secondYou can read more about what you can do using this module here
NOTE: In case somebody is wondering why this is not a code review (such as comments on the posted code), is because in the unedited question the author specifically asked if there is already a library for this.
Code Snippets
pip install num2words>>> from num2words import num2words
>>> num2words(42)
forty-two
>>> num2words(42, ordinal=True)
forty-secondContext
StackExchange Code Review Q#156590, answer score: 23
Revisions (0)
No revisions yet.