-1

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.

1
  • 1
    Could you be more specific on how you are trying to replace. Is it something like ' for CAPS is replaced?
    – voidpro
    Commented Jun 8, 2017 at 6:36

3 Answers 3

3

You can use regex:

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

Use re to replace patterns.

>>> 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'})
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:])

hope that is what you wanted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.