Python Practice › String Programs › Program 42

Number words to digits

EasyString Programs · 42 of 106

Write a Python program to convert number words into a number.

Advertisement
Input
"five four three two one"
Output
54321

Approach

  1. Map each word to its digit and join.

Solution

Python
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.

More string programs

← All 106 String Programs

Leave a Comment