Python 3中bytes对象调用split方法报TypeError的技术咨询
Let's break this down and fix that error quickly—you're already halfway there by identifying the bytes vs str mismatch!
The Root Cause
You're right that split() is a string method, but readBuffer.value is a bytes object (your type() check confirms this). When you try to call split(',') on bytes, Python throws that error because it expects a bytes separator, not a string one.
Two Simple Solutions
Since your goal is to extract the device ID (like 0 from your sample output), here are two straightforward approaches tailored to your use case:
1. Decode Bytes to String First (Most Readable)
Convert the bytes buffer to a regular string first, then handle splitting as you originally intended. This works perfectly because your device output uses ASCII-compatible characters:
readBuffer = ctypes.create_string_buffer(1024) # Make sure your C function fills readBuffer before this step! # Decode bytes to a string (use 'ascii' explicitly if you want to be precise) device_str = readBuffer.value.decode() # Clean up the trailing '\r;' and split into individual device entries device_entries = device_str.rstrip('\r;').split(';') # Extract the first device ID (loop through entries if multiple devices exist) first_device_id = device_entries[0].split(',')[0] print(f"Extracted Device ID: {first_device_id}")
2. Split Bytes Directly (No Decoding Needed)
If you prefer working with bytes without converting to a string, just use byte literals for your separators:
readBuffer = ctypes.create_string_buffer(1024) # Make sure your C function fills readBuffer before this step! # Strip trailing byte characters and split using byte separators device_bytes_entries = readBuffer.value.rstrip(b'\r;').split(b';') # Extract and decode the first device ID first_device_id = device_bytes_entries[0].split(b',')[0].decode() print(f"Extracted Device ID: {first_device_id}")
How This Works for Your Sample Output
Your sample readBuffer.value is b'0,NEWPORT 1936-R v1.2.2 04/06/12 SN22955\r;':
- Both methods first remove the trailing
\r;(orb'\r;'for bytes) - Split by
;(orb';') to get individual device entries - Split each entry by
,(orb',') to separate the ID from the description - The first part of the first entry is your desired device ID (
0)
内容的提问来源于stack exchange,提问作者Physicist

