Home > Net >  How to convert text to list in python
How to convert text to list in python

Time:11-27

Please add some context here. The question is missing.

input="""
intro: hey,how are you
i am fine

intro:
hey, how are you
Hope you are fine
"""

output= [['hey,how are you i am fine'],['hey, how are you Hope you are fine']]

for text in f:
    text = text.strip()

CodePudding user response:

We can use re.findall here in multiline mode:

inp = """intro: hey,how are you i am fine

intro: hey, how are you Hope you are fine"""

lines = re.findall(r'^\w :\s*(.*)$', inp, flags=re.M)
print(lines)

This prints:

['hey,how are you i am fine', 'hey, how are you Hope you are fine']

CodePudding user response:

I would look into something like regex or just use

input.split("intro:") or input.splitlines() to generate a list of strings. That would not result in the form you have below. But since your question is not clear thats the best i can do.

CodePudding user response:

You could do this by splitting the input data by the string intro:. This will give you a list of the required items. You can clean this up a little more by removing the \n and leading/trailing spaces.

As an example:

data = """
intro: hey,how are you
i am fine

intro:
hey, how are you
Hope you are fine
"""
only_intro = []
for intro in data.split("intro:"):
    if not intro.isspace():
        only_intro.append(intro.replace('\n', ' ').lstrip().rstrip())
print(only_intro)

which gives the following output:

['hey,how are you i am fine', 'hey, how are you Hope you are fine']
  • Related