帮我用Python写一个URL编码和字符互转的脚本
时间: 2023-06-26 07:05:38 浏览: 114
python字符串与url编码的转换实例
可以使用Python标准库中的urllib.parse模块来进行URL编码和字符互转。
URL编码:
```python
import urllib.parse
url = 'https://www.example.com/search?q=Python编程'
encoded_url = urllib.parse.quote(url)
print(encoded_url)
```
输出结果:
```
https%3A//www.example.com/search%3Fq%3DPython%E7%BC%96%E7%A8%8B
```
字符互转:
```python
import urllib.parse
encoded_str = 'https%3A//www.example.com/search%3Fq%3DPython%E7%BC%96%E7%A8%8B'
decoded_str = urllib.parse.unquote(encoded_str)
print(decoded_str)
```
输出结果:
```
https://www.example.com/search?q=Python编程
```
注意:在Python 2中,urllib库被分为urllib和urllib2两个库,URL编码和字符互转的方法名也略有不同,可通过以下方式实现:
```python
import urllib
url = 'https://www.example.com/search?q=Python编程'
encoded_url = urllib.quote(url)
print(encoded_url)
encoded_str = 'https%3A//www.example.com/search%3Fq%3DPython%E7%BC%96%E7%A8%8B'
decoded_str = urllib.unquote(encoded_str)
print(decoded_str)
```
阅读全文