How do I clear this line in python using stripe?

This is my input line

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

      

I have tried using strip

as below

string = string.strip("  \n")

      

However, when I print it, the data does not change

print repr(string)

      

Ideally I would like to format the data in a list, for example ["data here","another data","more data"]

I don't want to use functions regex

, how can I do this?

+3


source to share


3 answers


One liner can be:

In [20]: [s.strip() for s in string.splitlines() if s.strip()]
Out[20]: ['data here', 'another_data', 'more data']

      



to make it simple to loop:

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']

      

+3


source


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']

      

And don't use a string as a variable !!

+1


source


you can use 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']

      

+1


source







All Articles