这是我输入的字符串
string = "data here\n "\
"\n \n another_data\n \n more data\n"
我试过像下面这样使用strip
string = string.strip(" \n")
但是当我打印它时,数据没有改变
print repr(string)
理想情况下,我想像这样格式化列表中的数据 ["data here","another data","more data"]
我不想使用 regex
函数,我该如何完成?
最佳答案
一个衬垫可以是:
In [20]: [s.strip() for s in string.splitlines() if s.strip()]
Out[20]: ['data here', 'another_data', 'more data']
让它成为一个普通的for循环:
In [21]: res=[]
...: for s in string.splitlines():
...: clean_s = s.strip()
...: if clean_s:
...: res.append(clean_s)
...:
In [22]: res
Out[22]: ['data here', 'another_data', 'more data']
关于python - 如何用 strip 在 python 中清理这个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31624429/