如何在带有strip的python中清理这个字符串?

时间:2015-07-25 08:14:54

标签: 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函数,我怎样才能完成这项工作?

3 个答案:

答案 0 :(得分: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']

答案 1 :(得分:1)

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

结果:

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

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

答案 2 :(得分:1)

您可以使用>>> 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']

results = db.session.query(
    PendingPost.campaign_id.label('campaign_id'),
    Campaign.title.label('title'),
    sqlalchemy.func.count(PendingPost.status).label('status_count'),
).join(
    Campaign, Campaign.id == PendingPost.campaign_id,
).join(
    Areas, Areas.id == PendingPost.area_id
).filter(
    sqlalchemy.func.month(PendingPost.creation_date) == datetime.datetime.utcnow().month
).group_by(
    PendingPost.status,
    PendingPost.campaign_id,
).all()

print(results)
[(3, 'campaign title', 1),
 (4, 'campaign title', 1)]