3.python(第三天日记)
str常用操作
1.capitalize(首字母大写,其他小写)
s = 'wojiushiwo'
s1 = s.capitalize()
print(s1)
》Wojiushiwo
2.upper,lower(全部大写,全部小写)
s = 'wojiushiwo'
s1 = s.upper()
print(s1)
》WOJIUSHIWO
s = 'WOJIUSHIWO'
s1 = s.lower()
print(s1)
》wojiushiwo
3.center(居中)
s = 'wojiushiwo'
s1 = s.center(15) #括号里面只有数字默认为空格
print(s1)
》 wojiushiwo
s = 'wojiushiwo'
s1 = s.center(15,'*') #括号里面*可加可不加
print(s1)
》***wojiushiwo**
4.swapcase(大小写翻转)
s = 'WOjiuShIwo'
s1 = s.swapcase()
print(s1)
》woJIUsHiWO
5.startswith,endswith(以什么开头,以什么结尾)
s = 'wojiushiwo'
s1 = s.startswith('woj')
print(s1)
》True
s = 'wojiushiwo'
s1 = s.endswith('eo')
print(s1)
》False
6.title(单个首字母大写)
s = 'wo jiu*shi/wo' #非字母隔开的都认为是首字母
s1 = s.title()
print(s1)
》Wo Jiu*Shi/Wo
7.strip(去除收尾两端的空格,换行符,Tab键,字符)#任何东西都可以去除;没有返回值,去除原来元素的之后的值需要重新赋值(因为字符串不可变)
s = ' wojiu*shi/wo'
s1 = s.strip() #空格为空默认是空格
print(s1
》wojiu*shi/wo
s = '**wojiu*shi/wo'
s1 = s.strip('*') #括号中是什么就去除什么
print(s1)
》wojiu*shi/wo
s = 'wojiushiwo'
s1 = s.strip('o')
print(s1)
》wojiushiw
8.find,rfind,index,rindex(通过元素找索引) #find找不到返回-1,index找不到报错
s = 'wojiushiwo'
s1 = s.find('o') #默认从左到右
print(s1)
s2 = s.rfind('o') #从右往左
print(s2)
》1
》9
s = 'wojiushiwo'
s1 = s.find('i',2,4) #后两位是区间
print(s1)
s2 = s.rfind('i',-4,-1)
print(s2)
》3
》7
s = 'wojiushiwo'
s1 = s.index('i',2,4)
print(s1)
s2 = s.rindex('i',-4,-1)
print(s2)
》3
》7
9.count(寻找元素的个数,可切片)
s = 'wojiushiwo'
s1 = s.count('i',3,12)
print(s1)
》2
10.replace(替换)
s = 'wojiushiwo'
s1 = s.replace('i','火') #默认是替换全部
print(s1)
》woj火ush火
s = 'wojiushiwo'
s1 = s.replace('i','火',1) #最后的1是次数,几次由自己决定
print(s1)
》woj火ushiwo
11.split(分割) 默认以空格分割;没有返回值,分割成的列表需重新赋值(因为字符串不可变)
s = 'wo jiu shi wo'
s1 = s.split()
print(s1)
》['wo', 'jiu', 'shi', 'wo']
s = 'wo,jiu,shi,wo'
s1 = s.split(',')
print(s1)
》['wo', 'jiu', 'shi', 'wo']
s = 'wojiushiwo'
s1 = s.split('i')
print(s1)
》['woj', 'ush', 'wo']
s = 'wojiushiwo'
s1 = s.split('i',1) #1为次数
print(s1)
》['woj', 'ushiwo']
12.format(格式化输出)
第一种方法:
s = '我叫{},今年{},爱好{}'.format('MT',18,'母牛')
print(s)
》我叫MT,今年18,爱好母牛
第二种方法:
s = '我叫{0},今年{1},爱好{2},我依然叫{0},今年还是{1}'\
.format('MT',18,'母牛')
》我叫MT,今年18,爱好母牛,我依然叫MT,今年还是18
第三种方法:
s = '我叫{name},今年{age},爱好{hobby}'.format(age=18, name='MT', hobby='闷儿')
print(s)
》我叫MT,今年18,爱好闷儿
13.isalunm,isalpha,isdigit(判断)
name='123a'
print(name.isalnum()) #字符串由字母或数字组成
print(name.isalpha()) #字符串只由字母组成
print(name.isdigit()) #字符串只由数字组成
True
False
False
for 循环
s = 'abcd'
for i in s:
print(i)
》a
》b
》c
》d
索引与切片 : s[起始索引:截止索引:步长]
切片 顾头不顾腚
步长、反向步长