您的位置:首页 > 编程语言 > Python开发

Python重复、连接、索引、切片

2018-03-07 10:31 120 查看

字符串的重复

由*表示重复:
字符串文本的重复,使用
>>> 3*'py'
'pypypy'
>>> 'py'*3
'pypypy'
>>> 

变量的重复,使用
>>> a='py'
>>> b='thon'
>>> 3*a
'pypypy'
>>> 3*a+b*3
'pypypythonthonthon'
>>>

字符串的拼接

由+操作符连接
用于两个字符串文本,使用
>>> 'py'+'thon'
'python'
>>> 'py'+'th'+'on'
'python'

用于两个变量,使用
>>> a='py'
>>> b='thon'
>>> a+'thon'
'python'
>>> a+b
'python'
>>>

相邻的两个字符串文本自动连接。
>>> 'py''thon'
'python'
>>> 'py''th''on'
'python'
>>>
它只用于两个字符串文本,不能用于字符串表达式:
>>> a='py'
>>> b='thon'
>>> a 'thon'
  File "<stdin>", line 1
    a 'thon'
           ^
SyntaxError: invalid syntax
>>> ab
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'ab' is not defined
>>>

字符串的索引

Python没有单独的字符类型,一个字符就是一个简单的长度为1的字符串。左字符串的第一个字符索引为 0,而长度为 n 的字符串其最后一个字符的右界索引为 n。例如: 
 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1
文本中的第一行数字给出字符串中的索引点 0…6。
第二行给出相应的负索引。请注意 -0 实际上就是 0,所以它不会导致从右边开始计算。
所以索引的结果为:
>>> a='python'
>>> a[0]
'p'
>>> a[1]
'y'
>>> a[5]
'n'
>>> a[6]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> 
试图使用太大的索引会导致错误。

字符串的切片

切片是从 i 到 j 两个数值标示的边界之间的所有字符,切片后获得一个子字符串。
>>> a='python'
>>> a[0:6]
'python'
>>> a[0:5]
'pytho'
>>> a[1:5]
'ytho'
>>>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: