Python中如何使用decoder解码URL编码的字符串
发布时间:2023-12-28 03:51:37
Python中可以使用urllib库中的unquote函数来解码URL编码的字符串。unquote函数可以将URL编码的字符串解码为Unicode字符串。
以下是使用unquote函数解码URL编码字符串的示例:
import urllib # URL编码的字符串 encoded_str = "Hello%20World%21" # 解码URL编码字符串 decoded_str = urllib.parse.unquote(encoded_str) # 打印解码后的字符串 print(decoded_str)
运行以上代码,输出结果为:
Hello World!
在该示例中,我们使用了urllib.parse模块中的unquote函数来对URL编码的字符串进行解码。unquote函数将编码字符串"Hello%20World%21"解码为Unicode字符串"Hello World!",并通过print函数打印出来。
除了unquote函数外,urllib库中还提供了unquote_plus函数。unquote_plus函数与unquote函数类似,但它会将编码字符串中的"+"字符解码为空格字符" "。以下是使用unquote_plus函数解码URL编码字符串的示例:
import urllib # URL编码的字符串 encoded_str = "Hello+World%21" # 解码URL编码字符串 decoded_str = urllib.parse.unquote_plus(encoded_str) # 打印解码后的字符串 print(decoded_str)
运行以上代码,输出结果与之前示例相同:
Hello World!
在该示例中,我们使用了urllib.parse模块中的unquote_plus函数来对URL编码的字符串进行解码。unquote_plus函数将编码字符串"Hello+World%21"解码为Unicode字符串"Hello World!",并通过print函数打印出来。
总结来说,Python中可以使用urllib库中的unquote函数或unquote_plus函数来解码URL编码的字符串。unquote函数将编码字符串解码为Unicode字符串,而unquote_plus函数在解码时会将"+"字符解码为空格字符" "。以上是两个函数的基本用法及示例。
