Sbaffinator
Sbaffinator

Reputation: 1

Replace a char with a new line in Python

Im trying to replace in a .txt a charachter with itself and then go to the new line (in this case a '>' with a '> \r\n'). But the .replace function work as expected but the file has the strin '\r\n' instead of going new line. I feel dumb becouse i dont know what should i do.

import fileinput
filename = copyFile
text_to_search = '>'
replacement_text = '>' + '\\r\\n'
with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
    for line in file:
        print(line.replace(text_to_search, replacement_text), end='')

The input.txt contain :

    lorem><ipsum><doloret>impsum

After the replace contain :

    lorem>\r\n<ipsum>\r\n<doloret>\r\nimpsum

And im trying to get :

    lorem>
    <ipsum>
    <doloret>
    impsum

What im doing wrong?

I tryed:

replacement_text = '>' + '\\r\\n'

instead of

replacement_text = '> \\r\\n'

I know that should be the same but one user on StackOverflow managed to make it work like that. And i tryed to check on internet any other similar problem...

Upvotes: -1

Views: 611

Answers (2)

Bhargav
Bhargav

Reputation: 4062

As @roeen3o already proposed edit. here you can try other ways to achievbe your goal.

import re
string = open('a.txt', 'r').read()
string = re.sub(r'^><', '> <', string)
string = string.replace('\\r\\n', '')
print(string)

Also Gives #

lorem>

<ipsum>

<doloret>

impsum

Upvotes: 0

roeen30
roeen30

Reputation: 789

This line:

replacement_text = '>' + '\\r\\n'

Should be changed to this:

replacement_text = '>\r\n'

'\\r' results in a string with the literal backslash (\) character followed by an r. You want to use '\r', which is the escape sequence for a carriage return.

I also removed the + for you since you can just put CRLF in the same string literal after '>'.

Upvotes: 2

Related Questions