Using Python How Do You Convert Each Line to Be an Item in a List?

Problem scenario
You have a multi-line variable in Python. You want to convert each line to be its own item in a list. How do you make a multi-line string variable to become a list with the same contents?

Solution
Use the .splitlines() method to manipulate the string in this way.

Here is an example:

list_of_input="""a line here
another line there.
123 abc"""

print(type(list_of_input))
print("Now we convert…")
list_of_input = list(list_of_input.splitlines())
print(type(list_of_input))
print(list_of_input)

Leave a comment

Your email address will not be published. Required fields are marked *