Python 官方文档:入门教程 => 点击学习
目录前言:1.去掉左边空格2.去掉右边空格3.去掉左右两边空格4.去掉所有空格总结前言: 处理字符串时经常要定制化去掉无用的空格,python 中要么用存在的常规方法,或者用正则处理
处理字符串时经常要定制化去掉无用的空格,python 中要么用存在的常规方法,或者用正则处理
string = " * it is blank space test * "
print (string.lstrip())
result:
* it is blank space test *
string = " * it is blank space test * "
print (string.rstrip())
result:
* it is blank space test *
string = " * it is blank space test * "
print (string.strip())
result:
* it is blank space test *
有两种方式
eg1:调用字符串的替换方法把空格替换成空
string = " * it is blank space test * "
str_new = string.replace(" ", "")
print str_new
result:
*itisblankspacetest*
eg2:正则匹配把空格替换成空
import re
string = " * it is blank space test * "
str_new = re.sub(r"\s+", "", string)
print str_new
result:
*itisblankspacetest*
eg3:join()方法+split()方法
可以去除全部空格
# join为字符字符串合成传入一个字符串列表,split用于字符串分割可以按规则进行分割
>>> a = " a b c "
>>> b = a.split() # 字符串按空格分割成列表
>>> b ['a', 'b', 'c']
>>> c = "".join(b) # 使用一个空字符串合成列表内容生成新的字符串
>>> c 'abc'
# 快捷用法
>>> a = " a b c "
>>> "".join(a.split())
'abc'
到此这篇关于Python去掉空格的一些常用方式的文章就介绍到这了,更多相关python去掉空格内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: python去掉空格的一些常用方式
本文链接: https://www.lsjlt.com/news/164124.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0