How to remove ^ M from a text file and replace it with the next line

So, suppose I have a text file with the following contents:

Hello what is up. ^M
^M
What are you doing?

I want to remove ^Mand replace it with the next line. Therefore, my output will look like this:

Hello what is up. What are you doing?

How to do this in Python? Or if there is a way to do this using unix commands, then please let me know.

+5
source share
3 answers
''.join(somestring.split(r'\r'))

or

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

This assumes that you have carriage returns in your string, not the letter "^ M". If this is the literal string "^ M", then substituting r '\ r' with "^ M"

If you want newlines to disappear, use r '\ r \ n'

python, , , http://mihirknows.blogspot.com.au/2008/05/string-manipulation-in-python.html

, , , , , , .

+7

Try:

>>> mystring = mystring.replace("\r", "").replace("\n", "")

( "mystring" )

+6

use replace

x='Hello what is up. ^M\
^M\
What are you doing?'

print x.replace('^M','') # the second parameter  insert what you want replace it with 
0
source

All Articles