替换python字符串中的特定字符

时间:2017-06-08 06:29:52

标签: python string text

我有一个

的字符串

string = "create (:TestCustomer {'FIRSTNAME': 'James', 'LASTNAME': 'Comey', 'CITY': 'Sydney'})"

我想将'的特定集替换为%。它必须看起来像

string = "create (:TestCustomer {%FIRSTNAME%: 'James', %LASTNAME%: 'Comey', %CITY%: 'Sydney'})"

我正在尝试使用替换功能。但未能得到确切的结果。

3 个答案:

答案 0 :(得分:3)

您可以使用regex

>>> import re
>>> re.sub(r"'([^']+)': '([^']*)'", r"%\1%: '\2'", string)
"create (:TestCustomer {%FIRSTNAME%: 'James', %LASTNAME%: 'Comey', %CITY%: 'Sydney'})"

答案 1 :(得分:2)

使用re替换模式。

>>> import re
>>> s = "create (:TestCustomer {'FIRSTNAME': 'James', 'LASTNAME': 'Comey', 'CITY': 'Sydney'})"
>>> S=re.sub(r"\'([A-Z]*)\'",r"%\1%",s)
create (:TestCustomer {%FIRSTNAME%: 'James', %LASTNAME%: 'Comey', %CITY%: 'Sydney'})

答案 2 :(得分:0)

string = "create (:TestCustomer {'FIRSTNAME': 'James', 'LASTNAME': 'Comey', 'CITY': 'Sydney'})"

w = string.find('{')+ 1
x = w + 10;t = w + 22;y = w + 31;z = w + 43;q = w + 48
w1=string[w].replace("'",'%')
x1=string[x].replace("'",'%')
t1=string[t].replace("'",'%')
y1=string[y].replace("'",'%')
z1=string[z].replace("'",'%')
q1=string[q].replace("'",'%')

print(string[0:23]+w1+string[24:33]+x1+string[34:45]+t1+string[46:54]+y1+string[55:66]+z1+string[67:71]+q1+string[72:])

希望这就是你想要的。

相关问题