3.1.2. 字符串相比数值,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," he said.'
'"Yes," he said.'
>>> "\"Yes,\" he said."
'"Yes," he said.'
>>> '"Isn\'t," she said.'
'"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 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.
如果你前面带有 >>> 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
字符串可以由 >>> # 3 times 'un', followed by 'ium'
>>> 3 * 'un' + 'ium'
'unununium'
相邻的两个字符串文本自动连接在一起。: >>> 'Py' 'thon'
'Python'
它只用于两个字符串文本,不能用于字符串表达式: >>> prefix = 'Py'
>>> prefix 'thon' # can't concatenate a variable and a string literal
...
SyntaxError: invalid syntax
>>> ('un' * 3) 'ium'
...
SyntaxError: invalid syntax
如果你想连接多个变量或者连接一个变量和一个字符串文本,使用 >>> prefix + 'thon'
'Python'
这个功能在你想切分很长的字符串的时候特别有用: >>> text = ('Put several strings within parentheses '
'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'
字符串也可以被截取(检索)。类似于 C ,字符串的第一个字符索引为 0 。Python没有单独的字符类型;一个字符就是一个简单的长度为1的字符串。: >>> word = 'Python'
>>> word[0] # character in position 0
'P'
>>> word[5] # character in position 5
'n'
索引也可以是负数,这将导致从右边开始计算。例如: >>> word[-1] # last character
'n'
>>> word[-2] # second-last character
'o'
>>> word[-6]
'P'
请注意 -0 实际上就是 0,所以它不会导致从右边开始计算。 除了索引,还支持 切片。索引用于获得单个字符,切片 让你获得一个子字符串: >>> word[0:2] # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5] # characters from position 2 (included) to 5 (excluded)
'tho'
注意,包含起始的字符,不包含末尾的字符。这使得 >>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python' |
Archiver|手机版|笨鸟自学网 ( 粤ICP备20019910号 )
GMT+8, 2024-11-23 17:34 , Processed in 0.032645 second(s), 17 queries .