Search code examples
pythonpython-3.xstringpython-re

How Do You Unescape Special Characters In A Python String?


From spam\/eggs to spam/eggs

# This isn't working...
str = "spam\/eggs"
s = bytes(str, "utf-8").decode("unicode_escape")

print(s)
>>> spam\/eggs

# How to get "spam/eggs"

Solution

  • In python you can't use a '\' because python will think you will add something after it like '\t', '\n', etc. So you can use an extra backwards slash in the string: string = 'spam\\/eggs'

    I don't think this is the most effiencient way to do this a differnt way but you can do this:

    strs = 'spam\/eggs'
    print(strs)
    strs = strs.replace('\\','')
    print(strs)
    

    I just deleted the \ by replacing it with an empty string.