为何在字符串前加b可解决startswith的TypeError?加b的含义是什么?
解答你的两个Python问题
Hey there! Let's break down these two questions clearly—they're super common when navigating text vs binary data in Python.
问题2:前缀b的具体含义是什么?
Think of the b prefix as a label that tells Python: "This isn't regular text—it's raw binary data." Here's the breakdown:
- A normal string (like
'hello') is of typestr, made up of Unicode characters. It's designed for human-readable text, and under the hood uses UTF-8 encoding by default. - A string prefixed with
b(likeb'hello') is of typebytes, made up of raw integer values between 0 and 255. This type is meant for binary data scenarios: reading/writing files in binary mode, handling network packets, working with non-text file formats (like images or executables), etc.
For example, b'hello' translates to the byte sequence [104, 101, 108, 108, 111]—these are the ASCII byte values for each character in "hello".
问题1:为什么加b能解决startswith的TypeError?
That error boils down to type mismatch—Python is strict about comparing apples to apples here:
- If you're calling
startswithon abytesobject (say, data you read from a binary file or received over a network), the method expects its first argument to also be abytesobject (or a tuple ofbytesobjects). It won't accept a regularstrstring because the two types represent fundamentally different things. - When you add the
bprefix to your string, you convert it fromstrtobytes—now both the object callingstartswithand the argument you're passing are the same type. Python can now properly check if the bytes sequence starts with your specified prefix, and the error goes away.
Here's a quick example to make it concrete:
# 打开二进制文件,读取的内容是bytes类型 with open('my_file.bin', 'rb') as f: file_content = f.read() # ❌ 错误:传入str类型给bytes对象的startswith方法 # if file_content.startswith('file_header'): # ✅ 正确:传入bytes类型,匹配对象类型 if file_content.startswith(b'file_header'): print("Found the expected file header!")
内容的提问来源于stack exchange,提问作者Wazaa
相关产品推荐
相关产品推荐

