Replacing integers in string x without error handling

I am trying to find an easy way to replace integers in a string with x in python. I was able to get something good 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 gives 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 a way to get the result in a simpler one without relying on error / exception handling?

+4
source share
5 answers

Yes, using regex and the remodule:

import re

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

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

+8
source

str.isdigit ,

>>> data = "martian2015"
>>> "".join(["x" if char.isdigit() else char for char in data])
'martianxxxx'

isdigit True, . , , "x", .


, ,

>>> "".join("x" if char.isdigit() else char for char in data)
'martianxxxx'

, , , . . .

, str.join, .


​​, str.translate str.maketrans.

>>> mapping = str.maketrans("0123456789", "x" * 10)
>>> "martin2015".translate(mapping)
'martinxxxx'
>>> "10-03-2015".translate(mapping)
'xx-xx-xxxx'
>>> 

maketrans . , mapping translate, , mapping, .

+6

change isinstanceto.isdigit

string = "martian2015"
for i in string:
    if i.isdigit():
        string.replace(i, "x")

(or regular expressions, regex / re )

+3
source
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'
+1
source

If you do not know the method for processing the preliminary data, you can call the module stringto filter the num string.

import string

old_string = "martin2015"
new_string = "".join([s if s not in string.digits else "x" for s in old_string ])

print new_string
# martinxxxx

Although I know that my anwser is not the best solution, I want to offer different methods to help people solve problems.

+1
source

All Articles