nlgootee nlgootee - 2 months ago 8
Python Question

python replace will not replace "'" with "\'"

dctLineItems = InvFunctions.dctLineItems
for value in dctLineItems.values():
iORDER_ID = value[0]
iITEM_No = value[1]
iQUANTITY = value[2]
sTmp = value[3]
sTmp2 = sTmp.replace("'", "\'", 1)
#sTmp2 = connPy.escape(sTmp)
sITEM_Name = sTmp2
sPART_No = value[4]
fPRICE = value[5]
fPRICE = fPRICE.lstrip('$')
iDOGWOOD = value[6]
iADVANCED = value[7]


I have tested it extensively and replace works for just about anything except what I need it to do. When I try to replace " ' " with " \' " it doesn't do anything. Notice the commented line#8 connPy.escape(sTmp), it doesn't work either but that is going to be a separate question.

Answer

Another option: using Python's raw strings:

>>> "'hello'".replace("'", "\'")
>>> "'hello'"
>>>
>>> "'hello'".replace("'", "\\'")
>>> "\\'hello\\'"
>>>
>>> "'hello'".replace("'", r"\'")  # <- Note the starting r
>>> "\\'hello\\'"
Comments