Python - 在引号之间的字符串中插入数字

时间:2017-02-21 10:38:43

标签: python regex

我需要用数字本身替换字符串中的每个数字,但是在引号之间:

str = 'This is number 1 and this is number 22'

结果:

str= 'This is number "1" and this is number "22"'

我知道我可以使用这个正则表达式用另一个字符串替换字符串中的每个数字:

str = re.sub("\d", "x", str)

但这会给我:

str= 'This is number x and this is number xx'

如何用匹配的数字本身修改?

6 个答案:

答案 0 :(得分:6)

您可以使用\1构造来引用匹配的组。

>>> re.sub(r"(\d+)", r'"\1"', "This is number 1 and this is number 22")
'This is number "1" and this is number "22"'

注意使用原始字符串(以r为前缀)以避免必须转义反斜杠 - 您应该使用原始字符串来匹配模式,否则\d可能会被解释为转义符在将来。

此外,模式(\d+)匹配行中任意数量的数字,而不只是一个数字 - 如果不这样,就会生成This is number "1" and this is number "2""2"之类的字符串。

答案 1 :(得分:1)

您可以对替换模式中先前匹配的内容使用反向引用。语法为\g<Number>,其中Number是捕获的组的编号,或者是整个匹配的0。

由于您要将连续数字引用为一个而不是数字,您需要使用\d+作为模式,而不仅仅是\d

完整代码:

import re
str = 'This is number 1 and this is number 22'
pat = r'\d+'
repl = r'"\g<0>"'
print(re.sub(pat, repl, str))

请参阅http://ideone.com/x5uLte

答案 2 :(得分:1)

你甚至不需要使用正则表达式来解决这个问题:

>>> words = 'This is number 1 and this is number 22'
>>> " ".join('"{}"'.format(x) if x.isdigit() else x for x in words.split())
'This is number "1" and this is number "22"'

答案 3 :(得分:0)

你需要像这样捕捉你的号码:

(\d+)

替换为后引用(+围绕它的引号)"$1"

见这里:https://regex101.com/r/oXsFX7/1

答案 4 :(得分:0)

这样做:

s = re.sub("([0-9]+)",r'"\1"' , s)

另请避免使用str作为变量,因为str是Python中内置的string类型。

答案 5 :(得分:0)

试试这个,

import re
str = 'This is number 1 and this is number 22'
for s in str.split():
    if s.isdigit():
        str=re.sub(s, '"'+s+'"', str)
print str