Python : Can't read '\' as a string

Question:

I wanted to replace a string : ‘li\oa’ by ‘ext’
but I get this error

error: octal escape value 505 outside of range 0-0o377

I know that the problem is: string containing these chracters ‘\’, so the question is : How can i read these backslashes as a string.

df['col']= df['col'].replace(['li\oa'],['ext'], regex=True)
Asked By: Oumab10

||

Answers:

You have to escape the two backslashes by adding one “” for each one :

df['col']= df['col'].replace(['li\\oa'],['ext'], regex=True)
Answered By: Eduardo Soares

You can declare a string as raw (with an r in front of it) and it will print all its characters:

>>> string = r'li\oa'
>>> print string
'li\oa'

How to print backslash with Python?

Answered By: SaikaVA