龙空技术网

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

南冠客蓬莱 247

前言:

而今大家对“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 lineFirst line.Second line.

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

>>> print('C:\some\name')  					# here \n means newline!C:\someame>>> print(r'C:\some\name')  				# note the r before the quoteC:\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

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

标签: #python中单引号和双引号