Home > Software design >  Removing newline in the middle of a string, with replace()
Removing newline in the middle of a string, with replace()

Time:07-21

After looking at this Removing continuation characters in the middle of a string in Python and documentation on strip() and replace() im am super confused why i cant remove this newline in the middle of a string? I am taking into account that the \ is an escape character in string literals, and it still dont work with a raw string. What am i missing?

import re

data="Token\n Contract:\n 0x7e318f8d6560cd7457ddff8bad058d3073c1223f"
data2="Token\n Contract:\n 0x7e318f8d6560cd7457ddff8bad058d3073c1223f"

result = data.replace(r'\n', "")
result2 =data2.replace('\\n', "") 
print(result)
print(result2)

CodePudding user response:

You're trying to remove the literal string \n, not a newline. When you set result, you use a raw string, so escape sequences aren't processed. And when you set result2, you escape the backslash, so it's not an escape sequence.

Just use '\n' to make a newline.

data="Token\n Contract:\n 0x7e318f8d6560cd7457ddff8bad058d3073c1223f"
data2="Token\n Contract:\n 0x7e318f8d6560cd7457ddff8bad058d3073c1223f"

result = data.replace('\n', "")
result2 =data2.replace('\n', "") 
print(result)
print(result2)

DEMO

CodePudding user response:

You can also use regex to remove the \n in the string you have and \n should be in single quote

import re
data="Token\n Contract:\n 0x7e318f8d6560cd7457ddff8bad058d3073c1223f"

print(re.sub(r'\n', '', data)) 

Outputof the above code

Token Contract: 0x7e318f8d6560cd7457ddff8bad058d3073c1223f

Hope this helps thanks

  • Related