简体   繁体   中英

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"

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.

You could use regular expressions.

To remove especifically the special character \ you must specify to regex \ \

import re
myString = "spam\/eggs"
str2 = re.sub(r'\\', "", myString) # remove this character '\'
print(str2)
# spam/eggs

General purpose (remove specific characters):

import re
myString = "sp&a+m\/eg*gs"
str2 = re.sub(r'[\\&+*]', "", myString) # to remove what you want into the brackets
print(str2)
# spam/eggs
str = "spam/eggs"
str2 = bytes(str, "utf-8").decode("unicode_escape")
print(str2)

BTW: you should place the code in the question more carefully; you call a variable str then myString and the second variable str2 then str1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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