程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

Python中单引号和双引号的字符串操作

hfteth 2024-12-13 11:54:04 技术文章 15 ℃

>>> '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

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

Tags:

最近发表
标签列表