Python3.6.5 笔记:字符串中的转义字符\,\n,取消转义r,长字符串,字符串的索引

字符串可以 ('...')  ("...") 引用。  


 \ 是转义字符

例如在终端输入:

例子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.


\n 是用来换行的

例子4:

>>> s = 'First line.\nSecond line'
>>> print(s)
First line.
Second line

字符串前加r,使得字符串中的\用作普通字符
>>> 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.'


字符串可以被indexed,可以使用切片
>>> 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的长度


你可能感兴趣的:(python)