过滤输入字符串到数组python

时间:2018-06-13 08:37:13

标签: python arrays string filter

我正在尝试用以下字符串创建一个数组:

'25\r\n35\r\n5\r\n15\r\n25\r\n35\r\n5\r\n15\r\n25\r\n35\r\n5\r\n15\r\n25\r\n35\r\n5\r\n15\r\n25\r\n35\r\n5\r\n15\r\n25\r\n35\r\n5\r\n15\r\n25\r\n35\r\n5\r\n15\r\n25\r\n35\r\n5\r\n15\r\n25\r\n'

只需要添加数字。

我尝试了以下内容:

MyString.decode().strip('\r\n')

但后来我删除了'\ r \ n'

问题:有没有办法只过滤数字并将其放入数组中?

编辑:

array = [int(x) for x in data.split('\r\n')]

这似乎有效,但不是在我的情况下。

我正在使用蓝牙,因此我尝试读取输出流。

这是我的代码:

    def bluetooth_connect(self):
    bd_addr = "98:D3:31:FB:14:C8"   # MAC-address of our bluetooth-module
    port = 1
    sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
    sock.connect((bd_addr, port))

    data = ""
    while 1:
        try:
            data += sock.recv(1024)
            data_end = data.find('\n')
            array = []

            if data_end != -1:
                self.move_all_servos(data)
                data = data[data_end + 1:]
                array = [int(x) for x in data.split('\r\n')]

                for i in range(0, leng(array)):
                     print(i)

        except KeyboardInterrupt:
            break
    sock.close()

首先我得到了正确的数组,但过了一段时间它崩溃了这个错误:

array = [int(x) for x in data.split('\r\n')] ValueError: invalid literal for int() with base 10: ''

2 个答案:

答案 0 :(得分:0)

使用拆分。

s = '25\r\n35\r\n5\r\n15\r\n25\r\n35\r\n5\r\n15\r\n25\r\n35\r\n5\r\n15\r\n25\r\n35\r\n5\r\n15\r\n25\r\n35\r\n5\r\n15\r\n25\r\n35\r\n5\r\n15\r\n25\r\n35\r\n5\r\n15\r\n25\r\n35\r\n5\r\n15\r\n25\r\n'
s.split('\r\n')

答案 1 :(得分:0)

[int(x) for x in data.split('\r\n')]的问题是结果将在最后''之后的末尾包含空字符串\r\n。您可以使用过滤条件将其删除...

>>> [int(x) for x in data.split('\r\n') if x]
[25, 35, 5, 15, 25, 35, 5, 15, 25, 35, 5, 15, 25, 35, 5, 15, 25, 35, 5, 15, 25, 35, 5, 15, 25, 35, 5, 15, 25, 35, 5, 15, 25]

...或者只使用不带参数的data.split()

>>> [int(x) for x in data.split()]
[25, 35, 5, 15, 25, 35, 5, 15, 25, 35, 5, 15, 25, 35, 5, 15, 25, 35, 5, 15, 25, 35, 5, 15, 25, 35, 5, 15, 25, 35, 5, 15, 25]

从文档(强调我的):

S.split(sep=None, maxsplit=-1) -> list of strings
     

返回S中单词的列表,使用sep作为   分隔符字符串。如果给出maxsplit,最多是maxsplit   分裂完成。 如果未指定sep 或者为None,则为any   空白字符串是一个分隔符,是空字符串   已从结果中删除