python中单引号和双引号的区别(Python中单引号和双引号的字符串操作)

>>> 'spam eggs' # single quotes 'spam eggs' >>> 'doesn\'t' # use \' to escape the single quote... "doesn't" >>> "doesn't" # ...or use double quotes instead "doesn't" >>> '"Yes," they said.' '"Yes," they said.' >>> "\"Yes,\" they said." '"Yes," they said.' >>> '"Isn\'t," they said.' '"Isn\'t," they said.',我来为大家讲解一下关于python中单引号和双引号的区别?跟着小编一起来看一看吧!

python中单引号和双引号的区别(Python中单引号和双引号的字符串操作)

python中单引号和双引号的区别

>>> 'spam eggs' # single quotes 'spam eggs' >>> 'doesn\'t' # use \' to escape the single quote... "doesn't" >>> "doesn't" # ...or use double quotes instead "doesn't" >>> '"Yes," they said.' '"Yes," they said.' >>> "\"Yes,\" they said." '"Yes," they said.' >>> '"Isn\'t," they said.' '"Isn\'t," they said.'

在交互式解释器中,输出字符串括在引号中,特殊字符用反斜杠转义。虽然这有时看起来可能与输入不同(括起来的引号可能会更改),但这两个字符串是等效的。如果字符串包含单引号且不包含双引号,则字符串放在双引号中,否则用单引号括起来。 print()函数通过省略括起来的引号并打印转义字符和特殊字符来生成更具可读性的输出:

>>> '"Isn\'t," they said.' '"Isn\'t," they said.' >>> print('"Isn\'t," they said.') "Isn't," they said. >>> s = 'First line.\nSecond line.' # \n means newline >>> s # without print(), \n is included in the output 'First line.\nSecond line.' >>> print(s) # with print(), \n produces a new line First line. Second line.

如果不希望前面的字符被解释为特殊字符,则可以通过在第一个引号前添加一个原始字符串:\r

>>> print('C:\some\name') # here \n means newline! C:\some ame >>> print(r'C:\some\name') # note the r before the quote C:\some\name

字符串文本可以跨越多行。一种方法是使用三引号:或 。行尾会自动包含在字符串中,但可以通过在行尾添加 来防止这种情况发生。以下示例:"""...""" 和'''...'''

print("""\ Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to """)

生成以下输出(请注意,不包括初始换行符):

Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to

与其他语言不同,特殊字符单引号(‘ ’)和双引号(“ ”)具有相同的含义。两者之间的唯一区别是,在单引号中,您不需要转义(如果你已经转义),反之亦然。

,

免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com

    分享
    投诉
    首页