[英]python split string and pick substring
I am having a lot of trouble with the list returned by the split function in python. 我在python中的split函数返回的列表上遇到了很多麻烦。 I am probably being incredibly dense.
我可能非常的密集。
My python code is as follows 我的python代码如下
str = "XXX:YYY:ZZZ"
var+=1
ins = str.split(':')
print ins
When the script runs it returns the following result 脚本运行时返回以下结果
['XXX','YYY','ZZZ']
What i am struggling to do is pull out the string contained the second string in the list. 我正在努力做的是拔出列表中包含第二个字符串的字符串。 I would have thought the following code at the end of the python code would work.
我本以为python代码末尾的以下代码可以工作。
print ins[1]
but when i run it i get the following error 但是当我运行它时,出现以下错误
IndexError: list index out of range
Any help would be much appreciated 任何帮助将非常感激
full code 完整的代码
import time
ser = serial.Serial("COM3", 9600)
print ser
time.sleep(3)
print "Sending serial data"
var = 0
while var<=10:
str = ser.readline()
print str
var+=1
ins = str.split(':')
print ins
print ins[0]
if (str.split(':')=='end\n'):
break
if(ser.isOpen()):
print "Serial connection is still open."
ser.close();
print "Serial connectionnow terminated."
This returns 这返回
Serial<id=0x2a7fc50, open=True>(port='COM3', baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=False, rtscts=False, dsrdtr=False)
Sending serial data
Program Initiated
['Program Initiated\n']
Program Initiated
0:addsd:1
['0', 'addsd', '1\n']
0
1:addsd:2
['1', 'addsd', '2\n']
1
2:end:2
['2', 'end', '2\n']
2
Your code will not work in instances where the input you're analyzing has a length <= 1. 在您分析的输入长度小于等于1的情况下,您的代码将不起作用。
Try checking for that and handling it in your code. 尝试检查并在您的代码中进行处理。
One of the lines you are reading probably has a two '\\n' characters in a row. 您正在阅读的其中一行可能连续有两个'\\ n'字符。 When that string is read with readlines() and then spit it has no [1] index only a [0] index.
当使用readlines()读取该字符串然后吐出该字符串时,它没有[1]索引,只有[0]索引。
What output do you get for the program: 您会从程序中得到什么输出:
import serial // Or is serial a builtin for the version of python you are using?
print repr(serial.Serial("COM3", 9600))
Thanks, Marlen 谢谢,马伦
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.