如何使用strip在Python中清理字符串?

3

这是我的输入字符串

    string = "data here\n            "\
"\n        \n      another_data\n            \n            more data\n"

我曾经尝试使用以下代码进行字符串剪裁:strip
string = string.strip("  \n")

然而,当我打印它时,数据没有改变。
print repr(string)

理想情况下,我希望将数据格式化为像这样的列表["数据在这里","另一个数据","更多数据"]。我不想使用regex函数,如何完成此操作?
3个回答

3
一句话概括可以是:
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']

@Clodion 不,这是最好的一个。 - wolfgang

1
st = "data here\n            "\
    "\n        \n      another_data\n            \n            more data\n"
st = st.split()
print(st)

result:

['data', 'here', 'another_data', 'more', 'data']

不要使用字符串作为变量!!


2
为什么不使用“字符串”?这也不是原帖作者期望的输出;( - zhangxaochen
@clodion 这样会破坏数据,因为它是按独立的方式进行分割,而不是 OP 想要的。 - wolfgang
是的,对不起我犯了错误。 - Clodion

1
你可以使用re.split
>>> string = "data here\n            "\
"\n        \n      another_data\n            \n            more data\n"
>>> [i for i in re.split(r'\s*\n\s*', string) if i]
['data here', 'another_data', 'more data']

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接