简体   繁体   中英

Python .replace() not removing newline character

I'm trying to make a 'filter' of sorts to remove certain characters from a string.

I want to remove:
Parenthesis ()
Single Quotes '
Commas,
Newline Characters \n

The code I am using to do this looks like:

i = {
    'content':('\n\nPosh Pantry Boutique',)
}

table = dict.fromkeys(map(ord, ")(,'",))
i['content'] = (str(i['content']).translate(table)).replace('\n','')

#for readability, this code can also look like this:
#x = str(i['content'])
#x = x.translate(table)
#x = x.replace('\n','')
#i['content'] = x

print(i['content'])

However, the output of this code removes all the characters except the newline character.
\n\nPosh Pantry Boutique

I have tried to use.strip(), to no avail.
So, what am I doing wrong, or, is there no way to remove these characters?

All you need to do is add a single slash. \ is an escape character so you need to escape the slash. \\n will fix your issue.

Docs for your reference. https://docs.python.org/3/reference/lexical_analysis.html

i = {
    'content':('\n\nPosh Pantry Boutique',)
}

table = dict.fromkeys(map(ord, ")(,'",))
i['content'] = (str(i['content']).translate(table)).replace('\\n','')

#for readability, this code can also look like this:
#x = str(i['content'])
#x = x.translate(table)
#x = x.replace('\n','')
#i['content'] = x

print(i['content'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM