Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a multi-line string as one line in Python

Tags:

python

I am writing a program that analyzes a large directory text file line-by-line. In doing so, I am trying to extract different parts of the file and categorize them as 'Name', 'Address', etc. However, due to the format of the file, I am running into a problem. Some of the text i have is split into two lines, such as:

'123 ABCDEF ST
APT 456'

How can I make it so that even through line-by-line analysis, Python returns this as a single-line string in the form of

'123 ABCDEF ST APT 456'?

like image 897
user2662091 Avatar asked Aug 21 '13 23:08

user2662091


People also ask

How do I convert multiple lines to one line in Python?

To break one line into multiple lines in Python, use an opening parenthesis in the line you want to break. Now, Python expects the closing parenthesis in one of the next lines and the expression is evaluated across line boundaries.

How do you read a multiline string by line in Python?

Use the str. splitlines() method to read a multiline string line by line, e.g. for line in multiline_str.

How do you handle a multi line string in Python?

Multiline Strings with Triple Quotes A multiline string in Python begins and ends with either three single quotes or three double quotes. Any quotes, tabs, or newlines in between the “triple quotes” are considered part of the string. Python's indentation rules for blocks do not apply to lines inside a multiline string.

How do you join two lines in Python?

Use a backslash ( \ ) as a line continuation character If a backslash is placed at the end of a line, it is considered that the line is continued on the next line. Only string literals (string surrounded by ' or " ) are concatenated if written consecutively.


2 Answers

if you want to remove newlines:

"".join( my_string.splitlines())
like image 68
theodox Avatar answered Nov 10 '22 10:11

theodox


Assuming you are using windows if you do a print of the file to your screen you will see

'123 ABCDEF ST\nAPT 456\n'

the \n represent the line breaks.

so there are a number of ways to get rid of the new lines in the file. One easy way is to split the string on the newline characters and then rejoin the items from the list that will be created when you do the split

 myList = [item for item in myFile.split('\n')]
 newString = ' '.join(myList)
like image 42
PyNEwbie Avatar answered Nov 10 '22 11:11

PyNEwbie