Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python convert multiline to single line

Tags:

python

string

I want to convert Python multiline string to a single line. If I open the string in a Vim , I can see ^M at the start of each line. How do I process the string to make it all in a single line with tab separation between each line. Example in Vim it looks like:

  Serialnumber
 ^MName           Rick
 ^MAddress           902, A.street, Elsewhere

I would like it to be something like:

Serialnumber \t Name \t Rick \t Address \t 902, A.street,......

where each string is in one line. I tried

   somestring.replace(r'\r','\t')

But it doesn't work. Also, once the string is in a single line if I wanted a newline(UNIX newline?) at the end of the string how would I do that?

like image 505
user2441441 Avatar asked Aug 01 '13 21:08

user2441441


1 Answers

Deleted my previous answer because I realized it was wrong and I needed to test this solution.

Assuming that you are reading this from the file, you can do the following:

f = open('test.txt', 'r')
lines = f.readlines()
mystr = '\t'.join([line.strip() for line in lines])

As ep0 said, the ^M represents '\r', which the carriage return character in Windows. It is surprising that you would have ^M at the beginning of each line since the windows new-line character is \r\n. Having ^M at the beginning of the line indicates that your file contains \n\r instead.

Regardless, the code above makes use of a list comprehension to loop over each of the lines read from test.txt. For each line in lines, we call str.strip() to remove any whitespace and non-printing characters from the ENDS of each line. Finally, we call '\t'.join() on the resulting list to insert tabs.

like image 78
Vorticity Avatar answered Oct 29 '22 15:10

Vorticity