Files
Python_CookBook_repo/2.字符串和文本/20.在字节串上执行文本操作.py
2025-09-10 16:12:45 +08:00

34 lines
988 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import re
from pyasn1.codec.ber.decoder import decode
if __name__ == '__main__':
data = b'Hello World'
# 目前字节串已经支持大部分和字符串相同的操作
data05 = data[0:5]
print(data05)
is_startwith_hello = data.startswith(b'Hello')
print(is_startwith_hello)
data_sp = data.split()
print(data_sp)
data_suka = data.replace(b'Hello', b'Hello Suka')
print(data_suka)
# 唯一需要注意的是如果用re做了匹配那记得要用字节串的形式来匹配
data = b'foo:bar,spam'
try:
re.split('[:,]', data)
except:
print("匹配错误,换字节串匹配")
data_bsp = re.split(b'[:,]', data)
print(data_bsp)
# 字节串上的字符不能直接被识别需要先用ascii解码
print(data[0])
print(data.decode("ascii")[0])
# 我的建议是除非万不得已请不要用字节串处理文本统一使用ascii解码成字符串后再进行操作