从字节数组拆分字符串



我对python和PLC完全陌生。我以字节数组格式从西门子PLC的特定标签收到字符串,如(b'xfex07Testingx00x00x00x00x00x00x00x00x00x00x00x00'),我只需要字符串"测试";并在GUI中显示它。我不知道如何分割测试从这个字节数组。有人能帮我实现它吗?3.

发送前在PLC软件中设置为字符串格式。我已经完成了以下代码来读取标签值

import snap7
from snap7.util import *
import struct
import snap7.client
import logging
DB_NUMBER = ***
START_ADDRESS = 0
SIZE = 255                           
logging.basicConfig()
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
plc = snap7.client.Client()
plc.connect('My IP address',0,0)
plc_info = plc.get_cpu_info()
print(plc_info)
state = plc.get_cpu_state()
print(state)
db = plc.db_read(DB_NUMBER, START_ADDRESS, SIZE)
print(db)

我得到的输出是一个字节数组。

(b'xfex07Testingx00x00x00x00x00x00x00x00x00x00x00x00')

如果没有任何关于字符串是否总是在相同位置或类似的信息,我只能提供这个非常静态的答案:

# The bytearray you gave us
barray = bytearray(b'xfex07Testingx00x00x00x00x00x00x00x00x00x00x00x00')
# Start at index 2, split at first occurrence of 0byte and decode it to a string
print(barray[2:].split(b"x00")[0].decode("utf-8"))
>>> Testing
a = 'xfex07Testingx00x00x00x00x00x00x00x00x00x00x00x00'
b = a.split("x00")[0][2:]

将给b作为:

'Testing'

最新更新