Replacing digits with str.replace()

混江龙づ霸主 提交于 2020-01-03 09:04:14

问题


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?


回答1:


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




回答2:


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'



回答3:


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




回答4:


A solution using translate (source):

remove_digits = str.maketrans('0123456789', '%%%%%%%%%%')
'_u1_v1'.translate(remove_digits)  # '_u%_v%'


来源:https://stackoverflow.com/questions/19084443/replacing-digits-with-str-replace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!