Python中的高级字符串替换

时间:2017-07-31 11:38:56

标签: string python-3.x

我正在尝试替换文件中的字符串,即版本号4.0.0到5.0.0。但是,在使用替换方法时,24.0.0等版本也会发生变化,这是不可取的。

例如:我希望4.0.0在整个文件中更改为5.0.0。但是,24.0.0应保持不变。

我为简单的字符串替换编写了代码[fo is my file here]:

fo = open ('ex.txt', 'r')
for line in fo:
    print(line.replace('4.0.0', '5.0.0'))

示例输入:

This is a file
It contains a version number
That version number is 24.0.0
Ideally, it should remain 4.0.0
But 4.0.0 should get changed 

所需的输出是

This is a file
It contains a version number
That version number is 24.0.0
Ideally, it should remain 5.0.0
But 5.0.0 should get changed

给出的第二个解决方案是24.0.0正常工作。但是4.0.0.15正在变为5.0.0.15,这是不可取的

print(re.sub(r'\ b4.0.0 [^。]','5.0.0',line))工作,但它正在用5.0.0替换4,0.0。那也不可取。

请帮忙。

2 个答案:

答案 0 :(得分:0)

尝试使用正则表达式:

import re

test = "This is a file It contains a version number That version number is 24.0.0 Ideally, it should remain 4.0.0 But 4.0.0 should get changed"

print(re.sub(r'\b4.0.0', '5.0.0',test))

输出:

This is a file It contains a version number That version number is 24.0.0 Ideally, it should remain 5.0.0 But 5.0.0 should get changed

如果不匹配4.0.0.15,请使用:

print(re.sub(r'\b4.0.0[^.]', '5.0.0 ', test))

解释:

我们使用re模块,它是提供正则表达式匹配的python模块。

re.sub(pattern, repl, string):返回通过替换repl替换字符串中最左边非重叠模式而获得的字符串。

我们使用的pattern\b4.0.0[^.]

此部分\b4.0.0匹配空字符串后面的任何4.0.0。但那也匹配4.0.0.15。为了阻止这种情况发生,我们使用[^.]匹配除.之外的任何字符,因此,它不再与4.0.0.15匹配。

答案 1 :(得分:0)

为了澄清,正则表达式是一个强大的工具,我建议不要将它们用于日常字符串替换。

如果您知道在4.0.0之前有空格,您可以使用

line.replace(' 4.0.0 ' , ' 5.0.0 ')

(后面的空格用于取消4.0.0.5的替换

如果您不知道4.0.0之前有空格,那么正则表达式模式需要比穆罕默德的答案更复杂。

相关问题