[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
这篇文章主要介绍了Python 字符串去除空格的6种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,来一起学习吧。
在处理Python代码字符串的时候,我们常会遇到要去除空格的情况,所以就总结了多种方法供大家参考。
<>方法1:字符串strip()、lstrip()和rstrip()方法
# *_* coding : UTF-8 *_* username = ' 乐不思蜀 快乐学习 ' print(username.strip()) word=
'赵 钱 孙 李 周 吴 郑 王' word=''.join([i.strip(' ') for i in word]) print(word)
输出结果:
乐不思蜀 快乐学习
赵钱孙李周吴郑王
<>方法2:使用split()方法
# *_* coding : UTF-8 *_* word='编号 姓名 性别 年级 学校 奖项' list=word.split(' ') listnew=
[i for i in list if i!='' ] new=' '.join(listnew) print(new)
输出结果:
编号 姓名 性别 年级 学校 奖项
<>方法3:使用replace()方法
# *_* coding : UTF-8 *_* word= 'D:\mingrisoft\python\gobig\t' print(word.
replace('\t',''))
输出结果:
D:\mingrisoft\python\gobig
<>方法4:使用列表推导式
# *_* coding : UTF-8 *_* word='赵 钱 孙 李 周 吴 郑 王' word=''.join([i for i in word
if i !=' ']) print(word)
输出结果:
赵钱孙李周吴郑王
<>方法5:利用切片删除单个固定位置的字符
# *_* coding : UTF-8 *_* name = '伦纳德:31.2' print(name[:3] + name[4:])
输出结果:
伦纳德31.2
<>方法6:去除列表中的空元素
# *_* coding : UTF-8 *_* nba='哈登: 31.6 伦纳德: 31.2 乔治: 28.6 库里: 27.3 利拉德:26.9'
nbanew=nba.split(' ') nbaone=[i for i in nbanew if i !=''] print(nbaone)
输出结果:
[‘哈登:’, ‘31.6’, ‘伦纳德:’, ‘31.2’, ‘乔治:’, ‘28.6’, ‘库里:’, ‘27.3’, ‘利拉德:26.9’]
到此这篇关于Python 字符串去除空格的6种方法的文章就介绍到这了,更多相关Python
字符串去除空格的内容,请搜索CSDN以前的文章或继续浏览下面的相关文章希望大家以后多多支持!