简体   繁体   中英

Python - Convert the escape character of encoded string to %

I try to encode a Chinese string

Here is the code:

chinese = "公主连结"
print(chinese.encode()) -> b'\xe5\x85\xac\xe4\xb8\xbb\xe8\xbf\x9e\xe7\xbb\x93'

the value it returns is an encoded object, and '\x' is an escape character, how can I manipulate with this object like a string

Here is what I expected:

input: b'\xe5\x85\xac\xe4\xb8\xbb\xe8\xbf\x9e\xe7\xbb\x93'
output: %E5%85%AC%E4%B8%BB%E8%BF%9E%E7%BB%93

Could anyone help?

That looks like URL encoding. You can urllib.parse.quote to get the desired result:

chinese = "公主连结"
import urllib.parse

print(urllib.parse.quote(chinese))

Result:

%E5%85%AC%E4%B8%BB%E8%BF%9E%E7%BB%93

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