Python: Removing backslash in string?

懵懂的女人 提交于 2019-12-13 09:46:15

问题


I have following text output as a str():

"We\'ve ... here\'s why ... That\'s how ... it\'s"

As you see, there's always a "\" before the apostrophe.

Then, I tried following:

    text = text.replace("\", "")

SyntaxError: EOL while scanning string literal

Same happened with text.replace("\\", "") or text.strip("\").

What can I do to get rid of all \ in my text?

Thanks!

Solution:

\' is the way how Python outputs strings. Once you do print() or export the string, there's no issue.


回答1:


In Python 2.7.13, this code:

text = "We\'ve ... here\'s why ... That\'s how ... it\'s"
text = text.replace("\\", "")
print text

outputs We've ... here's why ... That's how ... it's

Are you using a different version of Python, or do you have a specific section of code to look at?

Edit:

I also wanted to mention that the apostrophe's have a backslash before them because it's an escape character. This essentially just means that you're telling the terminal that python is outputting to to interpret the apostrophe literally (in this situation), and to not handle it differently than any other character.

It's also worth noting that there are other good uses for backslashes (\n, or newline is one of the most useful imho).

For example:

text = "We\'ve ... here\'s why ...\nThat\'s how ... it\'s"
print text

outputs:

We've ... here's why ...
That's how ... it's

Not that the \n is interpreted as a request for the terminal to go to a newline before interpreting the rest of the string.



来源:https://stackoverflow.com/questions/47440270/python-removing-backslash-in-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!