How Do You Get a Multi-line Variable in Python to Be Treated as Lines and Not Characters?

Problem scenario
When a number of lines of text are read from a file, the Python program sees each line as such. When a number of lines of text are in the program itself, that is you use a multi-line variable assignment in a .py program, Python sees the characters individually and does not distinguish between the different lines. The len() function reflects these differences. You want the Python program to read the text in the program as if it were read from the "with open" and "readlines()" function line-by-line -- not character-by-character.

For example, your source text could be like this in a standalone .txt file:

foo bar 123 456
cat dog 999 888
horse cow 333 777

When you read the .txt file in the Python program, each line of text is treated as a separate item in a list. In a Python program, you could have an assignment like this:

data1 = """foo bar 123 456
cat dog 999 888
horse cow 333 777"""

But the three lines would be treated as a single string -- not a list. You want data1 to be three lines of text and the len(data1) function to return 3. You do not want to have separate .txt files for the .py program to open. You want everything in a self-contained .py file.

What do you need to do?

Solution
Use .splitlines() and list(). Here is an example:

list(data1.splitlines())

Leave a comment

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