11

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?

user2441441
  • 1,237
  • 4
  • 24
  • 45

8 Answers8

11

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.

Vorticity
  • 4,582
  • 4
  • 32
  • 49
  • I tried newstring = '\t'.join(somestring).replace('\r', '') But it gave me garbage value, when I read the file. Without this line, its readable (but in multi line) – user2441441 Aug 01 '13 at 23:55
  • Unfortunately I'm not reading it from a file. I'm not sure if I can use .strip(). I'm getting what I want in this 'somestring' and writing this 'somestring' to the file in a loop. So I want 'somestring' in one line before writing it in file. – user2441441 Aug 01 '13 at 23:58
  • Just in case you didn't notice, I deleted my previous answer. This answer uses strip() to remove both the "\n" and the "\r". I was hoping I would be quick enough to avoid you seeing my previous answer, but I guess I was wrong. – Vorticity Aug 01 '13 at 23:58
  • Okay, maybe I'm misunderstanding what you have. I think that I now understand that you have a single string that contains "^M" and you want to be able to print it to a file in a single line. Is this correct? – Vorticity Aug 02 '13 at 00:04
  • Yes. I fetch stuff into the string, and before writing it to a file I would like to have it in a single line. (So my file will have each string on new line) – user2441441 Aug 02 '13 at 00:27
  • Okay, for that purpose, I would do this: `newstring = '\t'.join([line.strip() for line in string.split('\n')])` this should split the string on all newline characters, strip out any extra junk like "^M", then join it all back together into a single line separated by tabs. – Vorticity Aug 02 '13 at 00:34
  • Okay. This works. But when I open it in gVim, the string is so long that it goes to the next line. I think that is just an editor issue though. Probably not the most efficient solution(since I will be writing 1000's of lines) but it works. Thanks. – user2441441 Aug 02 '13 at 00:51
  • One last tip, then. For VIM, if you want to make this easier to read, you can call `:set nowrap` and the text won't wrap to the next line. If you want to turn back on wrapping you can call `:set wrap`. Another option that I would suggest given what it appears that you are doing would be to quit using simple ascii files and start using json or xml. – Vorticity Aug 02 '13 at 02:54
6

You can replace "\r" characters by "\t".

my_string.replace("\r", "\t")
  • I do, sorry. I deleted that answer so I could put up a new one before you saw that one. Apparently I was too slow. See my new answer. It should work. – Vorticity Aug 01 '13 at 23:53
6

I use splitlines() to detect all types of lines, and then join everything together. This way you don't have to guess to replace \r or \n etc.

"".join(somestring.splitlines())
rouble
  • 16,364
  • 16
  • 107
  • 102
2

it is hard coding. But it works.

poem='''
If I can stop one heart from breaking,
I shall not live in vain;
If I can ease one life the aching,
Or cool one pain,
Or help one fainting robin
Unto his nest again,
I shall not live in vain.
'''


lst=list(poem)
str=''
for i in lst:
    str+=i
print(str)
lst1=str.split("\n")
str1=""

for i in lst1:
    str1+=i+" "
str2=str1[:-2]
print(str2)
Vlad
  • 8,225
  • 5
  • 33
  • 45
Madiha
  • 21
  • 1
0

This occurs of how VIM interprets CR (carriage return), used by Windows to delimit new lines. You should use just one editor (I personally prefer VIM). Read this: VIM ^M

Community
  • 1
  • 1
ep0
  • 710
  • 5
  • 13
  • Okay. So if I open a blank file in binary 'wb+' mode, when I read the string from notepad, it no longer has a newline like Vim does. Vim has exactly the same format given above i.e it reads a newline. So now how should I go about putting it in single line? – user2441441 Aug 01 '13 at 21:44
0

This trick also can be useful, write "\n" as a raw string. Like :

my_string = my_string.replace(r"\n", "\t")
Taohidul Islam
  • 5,246
  • 3
  • 26
  • 39
0

this should do the work:

def flatten(multiline):
    lst = multiline.split('\n')
    flat = ''
    for line in lst:
        flat += line.replace(' ', '')+' '
    return flat
EladTal
  • 2,167
  • 1
  • 18
  • 10
0
This should do the job:
string = """Name           Rick
 Address           902, A.street, Elsewhere"""

single_line = string.replace("\n", "\t")