- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How i can replace number with string using Python?
For this purpose let us use a dictionary object having digit as key and its word representation as value −
dct={'0':'zero','1':'one','2':'two','3':'three','4':'four', '5':'five','6':'six','7':'seven','8':'eight','9':'nine'
Initializa a new string object
newstr=''
Using a for loop traverse each character ch from input string at check if it is a digit with the help of isdigit() function.
If it is digit, use it as key and find corresponding value from dictionary and append it to newstr. If not append the character ch itself to newstr. Complete code is as follows:
string='I have 3 Networking books, 0 Database books, and 8 Programming books.' dct={'0':'zero','1':'one','2':'two','3':'three','4':'four', '5':'five','6':'six','7':'seven','8':'eight','9':'nine'} newstr='' for ch in string: if ch.isdigit()==True: dw=dct[ch] newstr=newstr+dw else: newstr=newstr+ch print (newstr)
The output is as desired
I have three Networking books, zero Database books, and eight Programming books.
Advertisements