简体   繁体   English

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

[英]Replacing specific characters in python string

I have a string which is 我有一个字符串是

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

I want to replace specific set of ' to % . 我想将特定的'替换为% It has to look like 它必须看起来像

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

I'm trying to use replace function. 我正在尝试使用替换功能。 But failed to get the exact result. 但是未能获得确切的结果。

You can use regex : 您可以使用regex

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

Use re to replace patterns. 使用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'})
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:])

hope that is what you wanted. 希望那是你想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM