[英]How to turn a string into a list of list?
我想通过 \\n 将字符串转换为列表列表,然后通过空格拆分子列表中的字符串。
例子:-
('We are champion\n We won the game\n')
想要的结果:-
[['We', 'are', 'champion'], ['We', 'won', 'the', 'game']]
我不知何故对函数 split 感到困惑,并发现我不能在子列表中使用 split 。
这应该适合你:
text = 'We are champion\n We won the game\n'
arr = []
for sentence in text.split('\n'):
sentence = sentence.strip()
if sentence:
arr.append(sentence.split(' '))
print(arr)
您可以使用splitlines
按新行拆分字符串。 然后循环将其split
为单词并附加到结果的array
。
提示:在执行拆分之前,您可以使用strip
来修剪字符串的空白空间。
txt = "We are champion\n We won the game\n"
xs = txt.strip().splitlines()
result = [];
for x in xs:
result.append(x.split())
print(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.