22

I want to make a new string by replacing digits with %d for example:

Name.replace( "_u1_v1" , "_u%d_v%d") 

...but the number 1 can be any digit for example "_u2_v2.tx"

Can I give replace() a wildcard to expect any digit? Like "_u"%d"_v"%d".tx"

Or do I have to make a regular expression?

johnsyweb
  • 136,902
  • 23
  • 188
  • 247
user1869582
  • 449
  • 1
  • 3
  • 10
  • it doesn't make sense you are replacing a value with any digit. you have to define the digit. if you have some function that defines the digit or takes input, pass in the variable that holds the value. For instance, Name.replace("_u1_v1", "_u" + variableName + "_v" + variableName). – JungJoo Sep 29 '13 at 23:31

6 Answers6

40

Using regular expressions:

>>> import re
>>> s = "_u1_v1"
>>> print re.sub('\d', '%d', s)
_u%d_v%d

\d matches any number 0-9. re.sub replaces the number(s) with %d

TerryA
  • 58,805
  • 11
  • 114
  • 143
16

You cannot; str.replace() works with literal text only.

To replace patterns, use regular expressions:

re.sub(r'_u\d_v\d', '_u%d_v%d', inputtext)

Demo:

>>> import re
>>> inputtext = '42_u2_v3.txt'
>>> re.sub(r'_u\d_v\d', '_u%d_v%d', inputtext)
'42_u%d_v%d.txt'
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
8

Just for variety, some non-regex approaches:

>>> s = "_u1_v1"
>>> ''.join("%d" if c.isdigit() else c for c in s)
'_u%d_v%d'

Or if you need to group multiple digits:

>>> from itertools import groupby, chain
>>> s = "_u1_v13"
>>> grouped = groupby(s, str.isdigit)
>>> ''.join(chain.from_iterable("%d" if k else g for k,g in grouped))
'_u%d_v%d'

(To be honest, though, while I'm generally anti-regex, this case is simple enough I'd probably use them.)

DSM
  • 342,061
  • 65
  • 592
  • 494
4

A solution using translate (source):

remove_digits = str.maketrans('0123456789', '%%%%%%%%%%')
'_u1_v1'.translate(remove_digits)  # '_u%_v%'
LoMaPh
  • 1,476
  • 2
  • 20
  • 33
1

If you want to delete all digits in the string you can do using translate (Removing numbers from string):

from string import digits
remove_digits = str.maketrans('', '', digits)
str = str.translate(remove_digits)

All credit goes to @LoMaPh

David Beauchemin
  • 231
  • 1
  • 2
  • 12
Ahmed
  • 41
  • 8
-1
temp = re.findall(r'\d+', text) 
res = list(map(int, temp))

for numText in res:
    text = text.replace(str(numText), str(numText)+'U')
  • 1
    Can you please explain your solution? – Gilfoyle Apr 15 '20 at 07:29
  • It would be helpful if you added some clarifying description of the solution you have suggested, instead of only providing code. Code can stand alone, but it's always better when you explain why you do something, instead of just how. Read more about writing a good answer here: https://stackoverflow.com/help/how-to-answer –  Apr 16 '20 at 01:01