如何将其中包含换行符的字符串转换为Python中的列表? [英] How to convert a string that has newline characters in it into a list in Python?
本文介绍了如何将其中包含换行符的字符串转换为Python中的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
在python中分割字符串
Possible Duplicate:
split a string in python
我要更改此内容
str = 'blue\norange\nyellow\npink\nblack'
对此:
list = ['blue','orange', 'yellow', 'pink', 'black']
我尝试了一些for和while循环,但无法做到这一点.我只希望在触发制作下一个元素时删除换行符.有人告诉我使用:
I tried some for and while loops and have not been able to do it. I just want the newline character to be removed while triggering to make the next element. I was told to use:
list(str)
给出
['b', 'l', 'u', 'e', '\n', 'o', 'r', 'a', 'n', 'g', 'e', '\n', 'y', 'e', 'l', 'l', 'o', 'w', '\n', 'p', 'i', 'n', 'k', '\n', 'b', 'l', 'a', 'c', 'k']
此后,我使用.remove()
,但只删除了一个'\n'
,并且使颜色拼写变得更加复杂.
After this I use .remove()
but only one '\n'
is removed and the code gets more complicated to spell the colors.
推荐答案
您要your_str.splitlines()
,或者可能只是your_str.split('\n')
使用for循环-仅供参考:
Using a for loop -- for instructional use only:
out = []
buff = []
for c in your_str:
if c == '\n':
out.append(''.join(buff))
buff = []
else:
buff.append(c)
else:
if buff:
out.append(''.join(buff))
print out
这篇关于如何将其中包含换行符的字符串转换为Python中的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文