python字符串普通操作

字符串拼接

  • 用加号连接
>>> 'zaime'+'hehe'
'zaimehehe'
>>> 
  • 直接放在一起,注意中间的空格数可以是0到无穷,但是必须是在同一行
>>> 'zaime'   'hehe'
'zaimehehe'
>>> 
  • 格式字符串连接
>>> 'zaime%s'%'hehe'
'zaimehehe'
>>> 

字符串切片

  • 获取单个字符串
>>> 'hehe'[0]
'h'
>>> 

  • 获取一个子串
#'str'[start:end:step]
#范围是左开右闭 [start,end)
#默认情况[0:len(str):1]
#step的正/负代表向右/左
>>> 'wo shi tr'[7:9]
'tr'
>>> 'wo shi tr'[3:6:2]
'si'
>>> 
>>> 'woshi'[1:4:-1]
''
>>> 'woshi'[2:1:-1]
's'
>>> 'woshi'[2:1]
''
#特别的[::-1]代表反转字符串
>>> 'woshi'[::-1]
'ihsow'
>>> 'woshi'[0::-1]
'w'
>>> 'woshi'[0:len('woshi'):-1]
''
>>> 'woshi'[:len('woshi'):-1]
''
原文地址:https://www.cnblogs.com/c-aha/p/10127753.html