Python 用 str.replace() 替换数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19084443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:48:39  来源:igfitidea点击:

Replacing digits with str.replace()

pythonreplaceexpression

提问by user1869582

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

我想通过替换数字来创建一个新字符串%d,例如:

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

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

...但数字1可以是任何数字,例如"_u2_v2.tx"

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

我可以给replace()一个通配符来期待任何数字吗?喜欢"_u"%d"_v"%d".tx"

Or do I have to make a regular expression?

还是我必须做一个正则表达式?

回答by Martijn Pieters

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

你不能; str.replace()适用于文字文本。

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'

回答by TerryA

Using regular expressions:

使用正则表达式:

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

\dmatches any number 0-9. re.subreplaces the number(s) with %d

\d匹配任何数字 0-9。re.sub将数字替换为%d

回答by DSM

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

(不过,说实话,虽然我通常反对正则表达式,但这种情况很简单,我可能会使用它们。)

回答by LoMaPh

A solution using translate(source):

使用translatesource)的解决方案:

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

回答by user3788060

temp = re.findall(r'\d+', text) 
res = list(map(int, temp))

for numText in res:
    text = text.replace(str(numText), str(numText)+'U')

回答by Ahmed

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

如果要删除字符串中的所有数字,可以使用translate从字符串中删除数字):

remove_digits = str.maketrans('', '', '0123456789')
str = str.translate(remove_digits)
all credit goes to @LoMaPh