Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replacing the integers in a string with x's without error handling

I have been trying to figure out a simple way to replace the integers within a string with x's in python. I was able to get something ok by doing the following:

In [73]: string = "martian2015"
In [74]: string = list(string)

In [75]: for n, i in enumerate(string):
   ....:     try:
   ....:         if isinstance(int(i), int):
   ....:             string[n]='x'
   ....:     except ValueError:
   ....:         continue

This actually yields something like the following:

In [81]: string
Out[81]: ['m', 'a', 'r', 't', 'i', 'a', 'n', 'x', 'x', 'x', 'x']
In [86]: joiner = ""

In [87]: string = joiner.join(string)

In [88]: string
Out[88]: 'martianxxxx'

My question is: is there any way of getting the result in a simpler manner without relying on error/exception handling?

like image 436
Abdou Avatar asked May 09 '15 14:05

Abdou


1 Answers

Yes, using regex and the re module:

import re

new_string = re.sub("\d", "x", "martin2015")

The string "\d" tells Python to search for all digits in the string. The second argument is what you want to replace all matches with, and the third argument is your input. (re.sub stands for "substitute")

like image 162
Michael0x2a Avatar answered Oct 24 '22 04:10

Michael0x2a