代码改变世界

字符串运算

2019-01-24 14:48  janease  阅读(68)  评论(0)    收藏  举报

字符拼接:+

>>> 'hello'+'word'
'helloword'

>>> 'hello'*5
'hellohellohellohellohello'
>>>

 

获取字符中的某一个字母,用字符串后面的【】表示,从0开始

如果输入正数,从0开始,从前往后数

如果是负数,从-1开始,从后往前数

>>> 'hello word'[5]
' '
>>> 'hello word!'[0]
'h'
>>>

>>> 'hello word!'[-1]
'!'

 获取到某个字符,重复n遍

>>> 'helll0'[0]*3
'hhh'
>>>

截取某个词组,Python,Python 给出一个语法:str【n:m】

从第几个字符,到低m个前一个字符

 

 

>>> 'hello word!'[0:-1]
'hello word'
>>> 'hello word!'[0:4]
'hell'
>>> 'hello word!'[0:5]
'hello'
>>>

>>> 'hello word'[6:11]
'word'

 

这个是从第n个字符截取到最后一个字符
>>> 'hello word'[6:]
'word'
>>>

>>> 'hello word'[:6]
'hello '
>>>