语法
for 临时变量 in 序列:for else
str1 asdasd for i in str1: print(i,end ) else: print() print( The code after loop ends normally )
output
asdasd The code after loop ends normally字符串 切片
切⽚是指对操作的对象截取其中⼀部分的操作。字符串、列表、元组都⽀持切⽚操作。
语法
name abcdefg print(name[2:5:1]) # cde print(name[2:5]) # cde print(name[:5]) # abcde print(name[1:]) # bcdefg print(name[:]) # abcdefg print(name[::2]) # aceg print(name[:-1]) # abcdef, 负1表示倒数第⼀个数据 print(name[-4:-1]) # def print(name[::-1]) # gfedcba查找
mystr hello world and itcast and itheima and Python print(mystr.find( and )) # 12 print(mystr.find( and , 15, 30)) # 23 print(mystr.find( ands )) # -1
基本一模一样
mystr hello world and itcast and itheima and Python # 结果 hello world he itcast he itheima he Python print(mystr.replace( and , he )) # 结果 hello world he itcast he itheima he Python print(mystr.replace( and , he , 10)) # 结果 hello world and itcast and itheima and Python print(mystr)split()
mystr hello world and itcast and itheima and Python # 结果 [ hello world , itcast , itheima , Python ] print(mystr.split( and )) # 结果 [ hello world , itcast , itheima and Python ] print(mystr.split( and , 2)) # 结果 [ hello , world , and , itcast , and , itheima , and , Python ] print(mystr.split( )) # 结果 [ hello , world , and itcast and itheima and Python ] print(mystr.split( , 2))
分割完的结果是list
join()str1 What a wonderful day! str1.split( ) print(str1) str1.join( ) print(str1)capitalize() title() lower() 大写转小写 upper() 小写转大写 ljust() rjust() center()



