-1

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)

Soma Juice
  • 369
  • 1
  • 11
  • Because you **don't want to** take into account that it's an escape character; you want to specify a string that **actually does** have a newline in it - just like the source data does. – Karl Knechtel Aug 06 '22 at 01:16

2 Answers2

1

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

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

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

y051
  • 184
  • 5