python字符串相关操作。


'''
    字符串相关操作
'''

# 1.字符串长度--len
A = '你好,2023'
print('字符串长度:',len(A))      #7

# 2.查找--find,--rfind,--index
A.find('2023')      #3  从左往右,索引从0开始
A.index('2023')     #3  从左往右,索引从0开始
A.rfind('2023')     #3  从右往左,索引从0开始

#find和index区别: 当不存在的时候,find返回-1,而index报错
A.find('2024')      #-1
A.index('2024')     #ValueError: substring not found

# 3.截取--[start:end:step]
print(A[:])     #你好,2023
print(A[:5])    #你好,202
print(A[:5:2])  #你,0

# 4.转换大小写
B = 'hello, Mike'
print(B.upper())    #HELLO, MIKE
print(B.lower())    #hello, mike

# 5.不能更改值
B[0] = 'H'      #TypeError: 'str' object does not support item assignment

# 6.startwith和endwith,返回逻辑值
B.startswith('H')   #False
B.startswith('he')   #True

# 7.去除空格,lstrip,rstrip,strip
C = '  , you are cute. '
print(C.strip())     #, you are cute.   去除左端空格
print(C.lstrip())    #, you are cute.   去除右端空格
print(C.rstrip())    #  , you are cute. 去除两端空格

# 8.分割split
C.split()       #[',', 'you', 'are', 'cute.'] 默认按照空格分隔
C.split(',')    #['  ', ' you are cute. ']

# 9.替换(old,new,number),(旧子字符串,新子字符串,个数)
D = 'I really really like you'
D.replace('really','truly',1)       #'I truly really like you'
D.replace('really','truly')         #'I truly truly like you'

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值