字符串的相关操作(切片/字母转换等)
作者:互联网
1.字符串的索引与切片
'''
s = 'ABCDLSESRF'
#索引
# s1 = s[0]
# print(s1)
# s2 = s[2]
# print(s2)
# s3 = s[-1] #倒序切片
# print(s3)
# s4 = s[-2]
# print(s4)
# #ABCD 切片 :顾头不顾尾
# s5 = s[0:4]
# print(s5)
# s6 = s[0:-1] #全部展示
# print(s6)
# s7 = s[:]
# s8 = s[0:]
# print(s7,s8)
# s9 = s[0:0] #结果为空
s = 'ABCDLSESRF' # s[首:尾:步长]
# s10 = s[0:5:2]
# print(s10)
s11 = s[4:0:-1] 结果:DCB A没有切出来 顾头不顾尾
print(s11)
s12 = s[3::-1]
print(s12)
s13 = s[3::-2]
print(s13)
s = 'ABCDLSESRF'
s14 = s[-1::-1]
print(s14)
s15 = s[::-1]
print(s15)
'''
2.首字母大写
s = 'alexWUsir'
s1 = s.capitalize() # 首字母大写
# print(s1)
3. 全大写,全小写
s2 = s.upper() #全部大写
s21 = s.lower() #全部小写
# print(s2,s21)
'''
例子:验证码验证
s_str= 'acEQ1'
you_input =input('请输入验证码,不区分大小写')
if s_str.upper() == you_input.upper():
print('输入成功')
else:
print('请重新输入')
'''
4.大小写翻转
# s3 = s.swapcase()
# print(s3)
5. 每个隔开(特殊字符或者数字)的单词首字母大写
# s = 'alex*egon-wusir'
# s4 = s.title()
# print(s4)
# s = 'fade,crazy*w4rri0r_songsong node_3'
# s4 = s.title()
# print(s4)
6.居中,空白填充
# s = 'alexWUsir'
# s5 = s.center(20,'~') #20表示长度 ’~‘表示空白用什么填
# print(s5)
# s = 'alex\tsir'
# s6 = s.expandtabs() /t 表示八个一位 不够的用空格替换 结果:alex(四个空格)sir
# print(s6)
7.长度
# s = 'alex二哥'
# #公共方法
# l = len(s)
# print(l)
8.以什么开头结尾 endswith
# s = 'alexWUsir'
# s7 =s.startswith('alex') #判断是不是alex开头
# s71 = s.startswith('e',2,5)
# print(s71)
'''
if s7:
pass
elif s.startswith('bl'):
pass
print(s7)
'''
9.
find 通过元素找索引,找不到返回-1
index通过元素找索引,找不到报错
# s = 'alexWUsir'
# s8 = s.find('A')
# s81 = s.index('A')
# print(s81,type(s8))
10. strip 默认删除前后空格
#strip rstrip lstrip
# s = 'alexWUsir%'
# s9 = s.strip('%')
# print(s9)
# s = ' *a%lexWUsi* r%'
# s91 = s.strip(' %*')
# print(s91)
例子:
# username = input('请输入名字:').strip()
# if username =='春哥':
# print('恭喜春哥发财')
11.统计
# s = 'alexaa wusirl'
# s10 = s.count('al')
# print(s10)
12.切片
# split str ---->list
# s = ';alex;wusir;taibai'
# l = s.split('a')
# print(l)
13.替换 replace
# s = '来看待街坊邻居复合大师街坊法好的撒见客户'
# s11 = s.replace('街坊','老王',1)
# print(s11)
标签:alex,字母,s7,大写,s4,切片,print,strip,字符串 来源: https://www.cnblogs.com/zs0621/p/16371781.html