Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将多行字符串的每一行发送到for循环中的列表_Python_String_List - Fatal编程技术网

Python 将多行字符串的每一行发送到for循环中的列表

Python 将多行字符串的每一行发送到for循环中的列表,python,string,list,Python,String,List,我有一个多行字符串,如下所示: something1 something2 something3 tableOut = 'something1\n' \ 'something2\n' \ 'something3' 我想把这个字符串的每一行都发送到一个列表中,这样result[0]=something1等等 我尝试过这样做: for line in tableOut: results.append(line.strip().split

我有一个多行字符串,如下所示:

something1
something2
something3
tableOut = 'something1\n' \
           'something2\n' \
           'something3'
我想把这个字符串的每一行都发送到一个列表中,这样
result[0]=something1
等等

我尝试过这样做:

for line in tableOut:
        results.append(line.strip().split('\n'))
但是,这会使字符串的每个字符都发送到列表中的唯一索引

例如:

[['s'], ['o'], ['m'], ['e'], ['t'], ['h'], ['i'], ['n'], ['g'], ['1']]

为什么这不起作用,如何将多行字符串的每一行发送到for循环中列表中的唯一索引?

tablout
是一个字符串:一个字符序列。命名循环索引
会产生误导,因为字符串上的迭代器会返回单个字符。这是你的主要问题

相反,
split
将字符串拆分为一个行列表——正如@sardok已经总结的那样。剥去各条线。您可以通过一个显式循环的列表来实现这一点

results = [strip(line) for line in tableOut.split('\n')]

tableOut
是一个字符串:一个字符序列。命名循环索引
会产生误导,因为字符串上的迭代器会返回单个字符。这是你的主要问题

相反,
split
将字符串拆分为一个行列表——正如@sardok已经总结的那样。剥去各条线。您可以通过一个显式循环的列表来实现这一点

results = [strip(line) for line in tableOut.split('\n')]

不清楚“多行”字符串是什么意思,但可以这样说:

something1
something2
something3
tableOut = 'something1\n' \
           'something2\n' \
           'something3'
然后你可以做:

result = []
for line in tableOut.split('\n'):
    result.append(line.strip())

这不是最具python风格的方式,但与您尝试的方式类似。

不清楚“多行”字符串是什么意思,但可以这样说:

something1
something2
something3
tableOut = 'something1\n' \
           'something2\n' \
           'something3'
然后你可以做:

result = []
for line in tableOut.split('\n'):
    result.append(line.strip())

这不是最符合python的方式,但与您尝试的方式类似。

查看字符串函数
split()
以获取行列表,然后列表y上的
for x in y
操作将把y中的每个条目分配给x-但要小心确保生成的行没有\r或\n等。因此,可能使用
strip()
关于分割的结果
[x_u.对于x_u.in[x.strip()对于x in data.splitlines()]如果x_u]
。对于tableOut.split('\n'):results.append(line.strip())
tableOut.split()
,代码的固定版本可以是
。(遍历字符串将产生字符。)
results=tableOut.splitlines()
?查看字符串函数
split()
若要获取行列表,则列表y中的x的
操作将把y中的每个条目分配给x-但要小心确保生成的行没有\r或\n等。因此,可能需要对拆分的结果使用
strip()
[x_u.for x_u.in[x.strip()for x in data.splitlines()]如果x_z]
。对于tableOut.split('\n'):results.append(line.strip())
tableOut.split()
,代码的固定版本可以是
。(遍历字符串会产生字符。)
results=tableOut.splitlines()
?我在问题中提供了一个多行字符串的示例。是的,好的,我可以解释。我在问题中提供了一个多行字符串的示例。是的,好的,我可以解释。