Python:删除字符串中的反斜杠? [英] Python: Removing backslash in string?

查看:141
本文介绍了Python:删除字符串中的反斜杠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将以下文本输出为str():

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

text.replace("\\",") text.strip("\")也是如此.

我该怎么办才能消除文本中的所有 \ ?

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

谢谢!

解决方案:

\'是Python输出字符串的方式.一旦执行print()或导出字符串,就没有问题了.

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

推荐答案

在Python 2.7.13中,此代码:

In Python 2.7.13, this code:

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

输出我们...这就是为什么...这就是...

您使用的是其他版本的Python,还是要查看特定的代码部分?

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

我还想提到撇号在它们前面加一个反斜杠,因为它是一个转义字符.从本质上讲,这只是意味着您要告诉终端python输出到的地方(在这种情况下)按字面意义来解释撇号,并且与其他任何字符都不能以不同的方式进行处理.

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.

值得注意的是,反斜杠还有其他很好的用法( \ n ,或者换行符是最有用的恕我直言之一).

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

例如:

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

输出:

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

不是 \ n 解释为在解释其余字符串之前,终端要求换行.

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

这篇关于Python:删除字符串中的反斜杠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆