第三章:常见的基础数据结构-字符串的常用方法
发布日期:2021-05-07 07:29:17 浏览次数:26 分类:精选文章

本文共 1281 字,大约阅读时间需要 4 分钟。

直接学习:https://edu.csdn.net/course/play/6861/326742

字符串的常用方法:
1、查询方法
str.index()
str.find()

price3 = '89.9元/桶'# 查询“元”所在的位置print(price3.index('元'))# 取出价格,并转换为浮点型print(float(price3[:price3.index('元')]))

备注:index()与find()区别,当查询不到元素时,index()会报错,find()会输出-1;

2、压缩方法
str.lstrip()
str.rstrip()
str.strip()

prodName = '乒乓球拍(红双喜) '# 压缩右侧的空白字符print(prodName.rstrip())price3 = '单价:18.9 元/Kg'# 取出价格并转换为浮点数print(float(price3[3:price3.index('元')].strip()))sentence = '&&&^_^很喜欢,给满分!(^-^)'# 剔除评论中首尾的特殊字符print(sentence.strip('&^_^(^-^)'))

3、替换方法

str.replace()

sentence = '别克英朗1.3t的排量家用足够了,1.3T对应的可是163马力!'# 将小写的t替换为大写的T  --  按值替换print(sentence.replace('t', 'T'))tel = '13612887890'# 隐藏手机号中间四位print(tel.replace(tel[3:7],'****'))

4、格式化插入方法

str.format(values)
values:指定格式化的值

info = '尊敬的刘先生,您的话费余额为6.78元,请及时充值,以免影响通话!'# 转换为格式化风格print('尊敬的{}{},您的话费余额为{}元,请及时充值,以免影响通话!'.format('刘','先生',6.78))# 保留两位有效数字的格式化print('ROC曲线下的AUC值为:{:.2f}'.format(0.8356444))# 生成5个有规则的网页链接for month in [1,2,3,4,5]:    print('http://tianqi.2345.com/t/wea_history/js/20190{0}/60008_20190{0}.js'.format(month))

5、分割方法

str.split(stp)
stp:指定待分割的分隔符

email = 'lsx1234567@163.com'# 将邮箱分割为邮箱名称和域名print(email.split('@'))info = '博佳花园 | 2室2厅 | 94.44平米 | 南 北 | 精装'# 取出二手房中的面积值,并转换为浮点型size = info.split('|')[2]print(float(size.strip()[:-2]))
上一篇:第三章:常见的基础数据结构-列表元组的介绍
下一篇:第三章:常见的基础数据结构-字符串切片的使用

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2025年04月16日 01时23分04秒