字符串可以 ('...'
) ("..."
) 引用。
\
是转义字符例如在终端输入:
例子1:
>>> 'doesn\'t'
"doesn't"
或者
>>> "doesn't"
"doesn't"
例子2:
>>> "\"Yes,\"he said."
'"Yes,"he said.'
或者
>>> '"Yes,"he said.'
'"Yes,"he said.'
例子3:(note:当在终端里输入如下命令时)
>>> '"Isn\'t."she said.'
'"Isn\'t."she said.'
>>> print('"Isn\'t."she said.')
"Isn't."she said.
例子4:
>>> s = 'First line.\nSecond line'
>>> print(s)
First line.
Second line
>>> print('C:\some\name')
C:\some
ame
>>> print(r'C:\some\name')
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'
>>> text = ('Put several strings within parentheses '
... 'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'
>>> word = 'Python'
>>> word[:2] + word[2:]
'Python'
下图可以用来记忆字符串index,left number作为相应字符的索引
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
字符串item不能改变
>>> word[0] = 'J' ... TypeError: 'str' object does not support item assignment
built-in function len(str)返回字符串str的长度