how to remove n from a python string

Asked

Viewed 10,008 times

1

I’m trying to delete control sequences (\n, \t, \u) of strings in Python and I can’t even with replace, nor with re.sub(). How could I do?

I tried, and they didn’t work :

p = re.sub('\n', '', p)


p.replace("\n","")
  • 1

    Can you put the whole code? With replace should work, so the error must be somewhere else in the code. You are capturing the return of the method, p = p.replace('\n', '')? If not, possibly that’s the mistake.

2 answers

5

With the replace is possible, just re-assign the output to the variable.

minha_string = "teste \n teste"
print(minha_string)
print("==============================")

minha_string = minha_string.replace('\n', '')
print(minha_string)

Exit:

teste
 teste
==============================
teste  teste

1

Simple, just use the function that removes control characters that are rstrip() right. Then in practice it would be:

SuaString = SuaString.rstrip()

Ready, now your string will no longer have the control characters! ;-)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.