Python:删除字符串中的反斜杠?

编程入门 行业动态 更新时间:2024-10-24 23:23:50
本文介绍了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:删除字符串中的反斜杠?

本文发布于:2023-11-06 14:35:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1563959.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:斜杠   字符串   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!