So suppose I have a text file of the following contents:
Hello what is up. ^M
^M
What are you doing?
I want to remove the ^M
and replace it with the line that follows. So my output would look like:
Hello what is up. What are you doing?
How do I do the above in Python? Or if there's any way to do this with unix commands then please let me know.
How can I remove ^M characters from text files? A. ^M are nothing more than carriage return, so it is easy to use the search and replace function of vim to remove them. That will do the job.
Open TextPad and the file you want to edit. Click Search and then Replace. In the Replace window, in the Find what section, type ^\n (caret, backslash 'n') and leave the Replace with section blank, unless you want to replace a blank line with other text. Check the Regular Expression box.
Remove \n From the String in Python Using the str. strip() Method. In order to remove \n from the string using the str. strip() method, we need to pass \n and \t to the method, and it will return the copy of the original string after removing \n and \t from the string.
''.join(somestring.split(r'\r'))
or
somestring.replace(r'\r','')
This assumes you have carriage return characters in your string, and not the literal "^M". If it is the literal string "^M" then substiture r'\r' with "^M"
If you want the newlines gone then use r'\r\n'
This is very basic string manipulation in python and it is probably worth looking at some basic tutorials http://mihirknows.blogspot.com.au/2008/05/string-manipulation-in-python.html
And as the first commenter said its always helpful to give some indication of what you have tried so far, and what you don't understand about the problem, rather than asking for an straight answer.
Try:
>>> mystring = mystring.replace("\r", "").replace("\n", "")
(where "mystring" contain your text)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With