如果要检查分隔符之间的字符,可以使用代码,然后将任何变量转换为
bool
类型。如果字符串不是空的,则意味着该字符串中存在某些内容,因此返回true。如果字符串为空,则返回false:
msgStr = 'RP000729SP001CT087ET02367EL048TP020DS042MF0220LT9.300000LN4.500000'
rpm = msgStr[msgStr.find("RP")+2:msgStr.find("SP")] # Outputs '000729'
Speed = msgStr[msgStr.find("SP")+2:msgStr.find("CT")] # Outputs '001'
coolent_temp = msgStr[msgStr.find("CT")+2:msgStr.find("ET")] # Outputs '087'
ETime = msgStr[msgStr.find("ET")+2:msgStr.find("EL")] # '02367'
e_load = msgStr[msgStr.find("EL")+2:msgStr.find("TP")] # '048'
throttle_pos = msgStr[msgStr.find("TP")+2:msgStr.find("DS")] # '020'
Distance = msgStr[msgStr.find("DS")+2:msgStr.find("MF")] # Outputs '042'
MAF = msgStr[msgStr.find("MF")+2:msgStr.find("LT")] # Outputs '0220'
Lat = msgStr[msgStr.find("LT")+2:msgStr.find("LN")] # Outputs '9.300000'
Lon = msgStr[msgStr.find("LN")+2:] # Outputs '4.500000'
bool(rpm) # Outputs True
bool(Speed) # Outputs True
bool(coolent_temp) # Outputs True
bool(ETime) # Outputs True
bool(e_load) # Outputs True
bool(throttle_pos) # Outputs True
bool(Distance) # Outputs True
bool(MAF) # Outputs True
bool(Lat) # Outputs True
bool(Lon) # Outputs True
您可以同时检查多个字段是否为空:
all_filled = bool(rpm) and bool(Speed) and bool(coolent_temp) and \
bool(ETime) and bool(e_load) and bool(throttle_pos) and bool(Distance) \
and bool(MAF) and bool(Lat) and bool(Lon)
代码的设置方式,如果使用
msgStr1
你已经得到了你想要的分离:
Example1_msgStr= "RP729SP14CT087ET2367EL48TP20DS42MF0220LT0.000000LN0.000000"
print (rpm, Speed, coolent_temp, ETime, e_load, throttle_pos, Distance, MAF, Lat, Lon)
Example2_msgStr= "RP72956SP134CT874ET02367EL458TP20DS042MF0220LT53.000LN45.00"
print (rpm, Speed, coolent_temp, ETime, e_load, throttle_pos, Distance, MAF, Lat, Lon)