python - 如何用 strip 在 python 中清理这个字符串?

标签 python regex

这是我输入的字符串

    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/

相关文章:

python - 如何在PyQt5中为对话框添加最小化和最大化图标?

Python 错误 : execute cannot be used while an asynchronous query is underway

Python:打开带有附件的 outlook 组合实例

python - 使用 mysite.urls 中定义的 URLconf,Django 尝试了这些 URL 模式,顺序为 :

regex - 发出运行 sed 以替换文件中的字符串

java - 正则表达式非贪婪但仍然

c# - 正则表达式除某些字符外的任何字符

python - 如何将 Python3 与 apache 一起使用,使用 MySQL 作为数据库语言?

javascript - 如何在JavaScript字符串replace(...)方法的第二个参数中引用搜索值?

regex - 验证字符串 # 后跟数字但 # 每次出现后都会增加