字符串编码和解码:Python中10个相关函数
Python中提供了许多字符串编码和解码相关的函数,使得我们可以轻松地处理各种字符集的字符串。下面我们介绍一下Python中10个常用的字符串编码和解码函数。
1. encode(encoding='utf-8', errors='strict')
该函数用于将一个字符串转换成指定编码下的字节流,并返回字节流对象。其中,encoding为转换编码名称,errors为解码错误的策略。
示例代码:
s = '中文'
b = s.encode('utf-8')
print(b) # b'\xe4\xb8\xad\xe6\x96\x87'
2. decode(encoding='utf-8', errors='strict')
该函数用于将一个字节流对象转换为指定编码下的字符串,并返回字符串对象。其中,encoding为编码名称,errors为解码错误的策略。
示例代码:
b = b'\xe4\xb8\xad\xe6\x96\x87'
s = b.decode('utf-8')
print(s) # 中文
3. str.encode和bytes.decode
这两种函数与上述函数作用相似,只是在使用上方便一些,可以直接用字符串类型的变量进行编码和解码。
示例代码:
s = '中文' b = s.encode() print(b) # b'\xe4\xb8\xad\xe6\x96\x87' s = b.decode() print(s) # 中文
4. ascii(obj)
该函数用于返回一个对象的ASCII码表示字符串。如果对象无法表示为ASCII码,则使用unicode码表示,并将其输出为ASCII码字符串。如果指定了obj的repr()函数返回的字符串,则repr()函数可用于自定义字符串表示方式。
示例代码:
a = ascii('中文')
print(a) # '\u4e2d\u6587'
a = ascii([1, 2, '中文'])
print(a) # '[1, 2, \'\\u4e2d\\u6587\']'
5. repr(obj)
该函数返回一个对象的字符串表示,用于调试和显示。返回的字符串通常可以使用eval()函数恢复原来的对象。
示例代码:
r = repr('中文')
print(r) # "'中文'"
r = repr([1, 2, '中文'])
print(r) # '[1, 2, \'中文\']'
6. format(obj, *args, **kwargs)
该函数用于格式化字符串,可以用于组合字符串和值。obj是一个格式化字符串,其中的占位符可以用args或kwargs对象的值替换。占位符中的{}用于指定位置参数,{x}与args[x]对应,{name}与kwargs['name']对应。
示例代码:
a = format('今天是{}年{}月{}日', 2022, 10, 12)
print(a) # 今天是2022年10月12日
b = format('我是{name},{age}岁', name='小明', age=18)
print(b) # 我是小明,18岁
7. encode_base64(input, output)
该函数用于对输入的字节流进行base64编码,并返回编码后的结果。output参数可选,如果指定了则将编码结果写入output对象,否则返回编码结果。
示例代码:
import base64
input = b'Hello, World!'
encode_data = base64.b64encode(input)
print(encode_data) # b'SGVsbG8sIFdvcmxkIQ=='
output = open('base64.txt', 'wb')
base64.encode_base64(input, output)
output.close()
input = open('base64.txt', 'rb')
decode_data = base64.decode_base64(input)
print(decode_data) # b'Hello, World!'
8. decode_base64(input, output)
该函数用于对输入的字节流进行base64解码,并返回解码后的结果。output参数可选,如果指定了则将解码结果写入output对象,否则返回解码结果。
示例代码:
import base64
input = b'SGVsbG8sIFdvcmxkIQ=='
decode_data = base64.b64decode(input)
print(decode_data) # b'Hello, World!'
input = open('base64.txt', 'rb')
decode_data = base64.decode_base64(input)
print(decode_data) # b'Hello, World!'
9. quote(string, safe=string.ascii_letters + string.digits + '-._~')
该函数用于将一个字符串进行url编码,并返回编码后的结果。safe参数用于指定要保留的字符,有些特殊字符可能会被urlencode删除,我们可以在这里指定保留。
示例代码:
import urllib.parse string = 'http://www.google.com/search?q=python' url = urllib.parse.quote(string) print(url) # http%3A//www.google.com/search%3Fq%3Dpython url = urllib.parse.quote(string, safe=':/') print(url) # http%3A//www.google.com/search%3Fq%3Dpython
10. unquote(string)
该函数用于将一个url编码后的字符串进行解码。
示例代码:
import urllib.parse string = 'http%3A//www.google.com/search%3Fq%3Dpython' url = urllib.parse.unquote(string) print(url) # http://www.google.com/search?q=python
以上是Python中10个常用的字符串编码和解码函数,这些函数在处理字符串编码和解码的时候非常有用。我们可以使用它们来处理各种字符集的字符串,并且也可以根据需要进行自定义字符串编码和解码。
