字符串相关方法

1.center,rjust,ljust,zfill

字符串.center(长度,填充字符)

字符串.rjust(长度,填充字符)

字符串.ljust(长度,填充字符)

字符串.zfill(长度)

str1='ab'
print(str1.center(9,'1')) # 11abc111
print(str1.rjust(10,'%')) # %%%%%%%%ab
print(str1.zfill(4)) # 00ab

# 长度小于字符串长度时,输出原字符串
print(str1.zfill(1)) # ab
print('abc'.rjust(2,'#')) # abc
print('abc'.ljust(2,'#')) # abc
2.count

字符串1.count(字符串2) — 统计字符串1中字符串2出现的次数

字符串1.count(字符串2,开始下标,结束下标)-----可以指定范围,在开始下标~结束下表

str1='ab'
print(str1.count('ab')) # 1
message='you see see , one day day'
print(message.count('a')) # 2
print(message.count('d',-7,-2)) # 2
print(message.count('d',-4)) # 1
3.find和index ----- rfind和rindex从右往左查找
# 字符串1.find(字符串2) --- 字符串2在字符串1第一次出现的位置
# 字符串1.index(字符串2) --- 字符串2在字符串1第一次出现的位置
message='you see see , one day day'
print(message.find('see')) # 4
print(message.index('see')) # 4
# # 找不到字符串2时返回不同,find返回-1,index报错
print(message.find('abc')) # -1
# print(message.index('abc')) # ValueError: substring not found
print(message.rfind('see')) # 8
print(message.rindex('see')) # 8
print(message.rfind('are')) # -1
4.isalnum,isalpha,isdigit,isnumeric,isspace,isupper,islower

a. 字符串.isalnum() ----判断字符串中是个否只包含数字,字母,中文
b. 字符串.isalpha() ----判断字符串中是否只包含字母和中文
c. 字符串.isdigit() —判断字符串是否是纯数字字符串(数字字符)
d. 字符串.isnumeric— 判断字符串是否是纯数字字符串(意义时数字的字符)
e. 字符串.isspace() -----判断字符串是否是空白字符
f. 字符串.isupper() ----- 判断字符串所有的字母是否都是大写字母
g. 字符串.islower() ----- 判断字符串中所有的字母是否都是小写字母

返回值都是布尔值

5.字符串.join(序列)----将序列中的元素通过指定的字符串合并成一个新的字符串(序列中的元素必须全是字符串)
# 练习:已经一个列表,将列表中所有的字符串用'=='连接成一个新的字符串
list1 = [100, 'abc', True, '你好', 'hello', 12.9]     # 'abc==你好==hello'
result='=='.join([x for x in list1 if type(x)==str])
print(result)
6.strip,lstrip,rstrip—去除字符串两边的空白
main_str ='    abc123   '
print(main_str,';',sep='')# '    abc123   ;'
print(main_str.strip(),';',sep='') # 'abc123;'
print(main_str.lstrip(),';',sep='')# 'abc123   ;'
print(main_str.rstrip(),';',sep='') # '    abc123;'
7.maketrans,translate

str.maketrans(字符串1,字符串2)----创建字符串1和字符串2的对应表

字符串.translate(对应表)-----按照对应表替换

message='今天周3,明天周4,周5就放假了,周6就可以出去玩了'
table=str.maketrans('0123456','一二三四五六日')
result=message.translate(table)
print(result) # 今天周四,明天周五,周六就放假了,周日就可以出去玩了
8.split

字符串1.split(字符串2)----将字符串1中所有的字符串2作为切割点进行切割

result='abcand123andmn'.split('and')
print(result) # ['abc', '123', 'mn']

字符串1.split(字符串2,N)----将字符串前N个字符串2作为切割点

result='abcMN123MNllasdMN'.split('MN',2)
print(result) # ['abc', '123', 'llasdMN']
9.replace

字符串1.replace(字符串2,字符串3)—将字符串1中的字符串2用字符串3替换

message='abcMN123MNllasdMN'
print(message.replace('MN','你好')) # abc你好123你好llasd你好

字符串1.replace(字符串2,字符串3,N)—将字符串1中前N个字符串2用字符串3替换

message='abcMN123MNllasdMN'
print(message.replace('MN','你好',2)) # abc你好123你好llasdMN
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

假发别带歪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值