目录
不管哪种语言,字符串数据类型,是必不可少的。今天骂我们学习python 中的字符串章节。
字符串定义:单引号和双引号,均可。
零、 字符串定义
单引号 ('...'
) 或双引号 ("..."
) 标识 。\
可以用来转义引号:
>>> 'spam eggs' # 单引号
'spam eggs'
>>> 'doesn\'t' # 转义字符 显示 单引号
"doesn't"
>>> "doesn't" # 内部含有单引号,外部使用双引号
"doesn't"
>>> '"Yes," he said.'
'"Yes," he said.'
>>> "\"Yes,\" he said." # 内外均是双引号,则使用转义字符 \
'"Yes," he said.'
>>> '"Isn\'t," she said.' # 内部含有单引号,外部使用单引号, 此处使用 转义字符 \n
'"Isn\'t," she said.'
在交互式解释器中,输出的字符串会用引号引起来,特殊字符会用反斜杠转义。虽然可能和输入看上去不太一样,但是两个字符串是相等的。如果字符串中只有单引号而没有双引号,就用双引号引用,否则用单引号引用。print() 函数生成可读性更好的输出, 它会省去引号并且打印出转义后的特殊字符:
>>> '"Isn\'t," she said.' # 内部含有双引号,那么使用单引号;内部含有单引号,那么使用\转义字符
'"Isn\'t," she said.'
>>> print('"Isn\'t," she said.')
"Isn't," she said.
>>> s = 'First line.\nSecond line.' # \n 表示开启新一行,这里完整显示。
>>> s # without print(), \n is included in the output
'First line.\nSecond line.'
>>> print(s) # with print(), \n produces a new line # print()函数,打印出了\n 功能
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
""")