python字符串的10个常用方法总结

本文总结了Python中字符串的10个常用方法,包括使用+和*连接字符串,通过len()计算长度,利用索引和切片操作,find()查找子串位置,replace()替换子串,强制类型转换,format()格式化输出,split()分割字符串,count()统计字符出现次数,以及strip()忽略特殊字符并转为小写。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 字符串用 + 和 * 连接

+连接

what_he_does = ' plays '
his_instrument = 'guitar'
his_name = 'Robert Johnson'
artist_intro = his_name + what_he_does + his_instrument
print(artist_intro)

# echo
Robert Johnson plays guitar

*连接

word = 'love'
words = word*3
print(words)

# echo
lovelovelove

2 len(string)——计算字符串的长度

word = 'love'
words = word*3
print(len(words))

# echo
12

3 string[left,right]——字符串的分片与索引

字符串有点像一个元组,所以可以用string[index]的方式进行索引

print(name[5:])			# 右侧不写,代表到最后
'me is Mike'
print(name[:5])			# 注意是左闭右开,所以第5个是取不到的
'My na'

从左到右,是和数组一样,从0开始的,而从右

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值