Removing newline in the middle of a string, with replace()

Question:

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="Tokenn Contract:n 0x7e318f8d6560cd7457ddff8bad058d3073c1223f"
data2="Tokenn Contract:n 0x7e318f8d6560cd7457ddff8bad058d3073c1223f"

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

Asked By: SomaJuice

||

Answers:

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="Tokenn Contract:n 0x7e318f8d6560cd7457ddff8bad058d3073c1223f"
data2="Tokenn Contract:n 0x7e318f8d6560cd7457ddff8bad058d3073c1223f"

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

DEMO

Answered By: Barmar

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

import re
data="Tokenn Contract:n 0x7e318f8d6560cd7457ddff8bad058d3073c1223f"

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

Outputof the above code

Token Contract: 0x7e318f8d6560cd7457ddff8bad058d3073c1223f

Hope this helps thanks

Answered By: y051
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.