首页 > 解决方案 > 单引号,双引号作为 Python 输入值

问题描述

我使用了以下命令,每次都将不同的值存储在变量中。

name=input('enter your name:')
enter your name:'' (two single quotes)
name
"''" (this is how it is displayed after I type 'Name' and press 'Enter')

name=input('enter your name:')
enter your name:"" (two double quotes)
name
'""' (this is how it is displayed after I type 'Name' and press 'Enter')

name=input('enter your name:')
enter your name:"'"' (double, single, double, single)
name
'"\'"\'' (this is how it is displayed after I type 'Name' and press 'Enter')

name=input('enter your name:')
enter your name:'"'" (single, double, single, double)
name
'\'"\'"' (this is how it is displayed after I type 'Name' and press 'Enter')

变量“名称”中的 \ 表示什么,为什么会出现?

标签: pythonpython-3.x

解决方案


它可以在单引号字符串中转义单引号。这种“转义”允许您在字符串中使用单引号和/或双引号。您可以通过在用单引号引用的字符串中使用双引号来解决此问题,反之亦然。但是,如果您有一个带有单引号和双引号的字符串,这将不再起作用。所以你现在已经使用转义了。

Python 控制台只希望您看到变量,而不是变量的内容,这就是您看到转义的原因。您也可以仅使用 print 显示字符串,而不会看到转义,因为您现在只是按原样查看字符串。

所以,只需使用print(name)


推荐阅读