python字符串在单引号前添加反斜杠 [英] python string adding backslash before single quotes

查看:504
本文介绍了python字符串在单引号前添加反斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含这样引号的字符串:

string = "\"这是我妈妈的花瓶\",凯文说."

问题是当我将它用作 python 中的字符串时,它会在单引号前添加一个反斜杠,如下所示:

<预><代码>>>>细绳这是我妈妈的花瓶,"凯文说.>>>

为什么会发生这种情况,我该怎么办?

解决方案

说明

您看到的是由 生成的字符串表示repr 函数.repr 以有效的python 文字的方式输出字符串;换句话说,您可以将 repr(string) 的输出复制/粘贴到 python 程序中,而不会出现语法错误:

<预><代码>>>>细绳这是我妈妈的花瓶,"凯文说.>>>这是我妈妈的花瓶,"凯文说.# 这是有效的python代码!这是我妈妈的花瓶,"凯文说.

因为您的字符串同时包含单引号 ' 和双引号 ",python 必须转义其中一个引号以生成有效的字符串文字.同样的方式你用反斜杠转义了双引号:

\这是我妈妈的花瓶\",凯文说.

Python 选择转义单引号:

'这是我妈妈的花瓶",凯文说.'

当然,这两个字符串完全相同.那些反斜杠仅用于转义目的,它们实际上并不存在于字符串中.您可以通过 printing 确认这一点字符串,输出字符串的真实值:

<预><代码>>>>打印(字符串)这是我妈妈的花瓶,"凯文说.

解决方案

没有什么可以解决的!你还在这里做什么?向上滚动并再次阅读说明!

I have a string that contains quotes like this:

string = "\"This is my mom's vase\", said Kevin."

Problem is when I use it as a string in python it adds a backslash before single quotes, as seen here:

>>> string
'"This is my mom\'s vase", said Kevin.'
>>>

Why is this happening and what can I do about it?

解决方案

The Explanation

What you're seeing is the representation of your string as produced by the repr function. repr outputs strings in such a way that they're valid python literals; in other words, you can copy/paste the output of repr(string) into a python program without getting a syntax error:

>>> string
'"This is my mom\'s vase", said Kevin.'
>>> '"This is my mom\'s vase", said Kevin.'  # it's valid python code!
'"This is my mom\'s vase", said Kevin.'

Because your string contains both single quotes ' and double quotes ", python has to escape one of those quotes in order to produce a valid string literal. The same way you escaped your double quotes with backslashes:

"\"This is my mom's vase\", said Kevin."

Python instead chooses to escape the single quotes:

'"This is my mom\'s vase", said Kevin.'

Of course, both of these strings are completely identical. Those backslashes are only there for escaping purposes, they don't actually exist in the string. You can confirm this by printing the string, which outputs the string's real value:

>>> print(string)
"This is my mom's vase", said Kevin.

The Solution

There's nothing to solve! What are you still doing here? Scroll up and read the explanation again!

这篇关于python字符串在单引号前添加反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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