Replacing The Integers In A String With X's Without Error Handling
Solution 1:
Yes, using regex and the re module:
importrenew_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")
Solution 2:
You can use the str.isdigit function and list comprehension, like this
>>> data = "martian2015"
>>> "".join(["x"ifchar.isdigit() elsecharforcharin data])
'martianxxxx'The isdigit function will return True if all the characters in it are numeric digits. So, if it is a digit, then we use "x" otherwise we use the actual character itself.
You can actually use generator expression instead of list comprehension to do the same, like this
>>> "".join("x"ifchar.isdigit() elsecharforcharin data)
'martianxxxx'The only difference is generators are lazy evaluated, unlike the list comprehension which builds the entire list. The generator will give values only on demand. Read more about them here.
But in this particular case, with str.join, the list is built anyway.
If you are going to do this kind of replacement often, then you might want to know about str.translate and str.maketrans.
>>>mapping = str.maketrans("0123456789", "x" * 10)>>>"martin2015".translate(mapping)
'martinxxxx'
>>>"10-03-2015".translate(mapping)
'xx-xx-xxxx'
>>>The maketrans builds a dictionary with the character codes of values in the first string and the corresponding character in the second string. So, when we use the mapping with the translate, whenever it finds a character in the mapping, it will simply replace it with the corresponding value.
Solution 3:
change isinstance to .isdigit
string = "martian2015"for i instring:
if i.isdigit():
string.replace(i, "x")
Solution 4:
In [102]: import string
In [103]: mystring
Out[103]: 'martian2015'
In [104]: a='x'*10
In [105]: leet=maketrans('0123456789',a)
In [106]: mystring.translate(leet)
Out[106]: 'martianxxxx'Solution 5:
If you don't know advance data process method, you can invoke string module to filter num string.
import string
old_string = "martin2015"
new_string = "".join([s if s notinstring.digits else"x"for s in old_string ])
print new_string
# martinxxxxAlthough I know my anwser is not the best solution, I want to offer different methods help people solve problems.
Post a Comment for "Replacing The Integers In A String With X's Without Error Handling"