2

I have a need to convert a string to an int and back after doing some processing. And the string has to be in words like below:

45 - forty five
99 - ninety nine

I searched everywhere for a hint but couldn't find any. I know the obvious switch-case logic but I am curious if theres a more intelligent way doing it with less lines of code.

Josh Lee
  • 171,072
  • 38
  • 269
  • 275
HasIq.
  • 117
  • 1
  • 8
  • 3
    You'll have fun reading this code-golf: http://stackoverflow.com/questions/309884/code-golf-number-to-words – Fábio Diniz Aug 12 '11 at 14:01
  • well logically yes. This is a tracker which tracks the number of vehicles in front of the user's car. So the number naturally can't be in the millions! :) – HasIq. Aug 12 '11 at 14:19
  • possible duplicate of http://stackoverflow.com/questions/493174/is-there-a-way-to-convert-number-words-to-integers-python – jterrace Aug 12 '11 at 15:44

2 Answers2

2

use num2words, see(https://www.geeksforgeeks.org/python-number-to-words-using-num2words/)

  from num2words import num2words
  def num2word(num):
     """
      convert numbers in a string to their word representation
     """  
     try:
         return num2words(num, lang='en_IN')
     except:
         return num
Golden Lion
  • 3,840
  • 2
  • 26
  • 35
1

Have a look at http://pypi.python.org/pypi/PyNum2Word

Alexis Métaireau
  • 10,767
  • 5
  • 24
  • 34