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?
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With