Python Practice › String Programs › Program 42
Number words to digits
Write a Python program to convert number words into a number.
Input
"five four three two one"
Output
54321
Approach
- Map each word to its digit and join.
Solution
words = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]text = "five four three two one"digits = "".join(str(words.index(w)) for w in text.split())print(int(digits))Output
54321
Line by line
Line 4
words.index(w) is the digit for each word.
Learn the concept
New to this topic? Read the lesson, then come back.