Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing digits with str.replace()

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?

like image 836
user1869582 Avatar asked Sep 29 '13 23:09

user1869582


People also ask

How do you replace a digit in a string?

Method #1 : Using replace() + isdigit() In this, we check for numerics using isdigit() and replace() is used to perform the task of replacing the numbers by K.

What does str replace do in Python?

The replace() method returns a copy of the string where the old substring is replaced with the new substring.

How do you replace a number in a word in Python?

You find the numbers using regex and then you can convert the number to words with using num2words package. And simply replace them.


5 Answers

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

like image 138
TerryA Avatar answered Oct 21 '22 21:10

TerryA


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'
like image 28
Martijn Pieters Avatar answered Oct 21 '22 21:10

Martijn Pieters


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.)

like image 20
DSM Avatar answered Oct 21 '22 19:10

DSM


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

like image 25
Ahmed Avatar answered Oct 21 '22 19:10

Ahmed


A solution using translate (source):

remove_digits = str.maketrans('0123456789', '%%%%%%%%%%')
'_u1_v1'.translate(remove_digits)  # '_u%_v%'
like image 40
LoMaPh Avatar answered Oct 21 '22 21:10

LoMaPh