您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Python如何删除字符串中所有空格

2024/3/2 20:35:12发布27次查看
在python中删除字符串中所有空格有:使用replace()函数、使用split()函数+join()函数、使用python正则表达式。下面本篇文章就来具体介绍一下这些方法,希望对大家有所帮助。【相关视频教程推荐:python教程】
使用replace()函数
我们可以使用replace()函数,把所有的空格( )替换为()
def remove(string): return string.replace(" ", ""); string = ' h e l l o ! ';print("原字符串:"+string) ;print("\n新字符串:"+remove(string)) ;
输出:
使用split()函数+join()函数
split()函数会通过指定分隔符对字符串进行切片,返回分割后的字符串的所有单字符列表。然后,我们使用join()函数迭代连接这些字符。
def remove(string): return "".join(string.split());string = 'w o r l d ';print("原字符串:"+string) ;print("\n新字符串:"+remove(string)) ;
输出:
使用python正则表达式
python 自1.5版本起增加了re 模块,它提供 perl 风格的正则表达式模式。
re 模块使 python 语言拥有全部的正则表达式功能。
#导入re 模块import redef remove(string): pattern = re.compile(r'\s+'); return re.sub(pattern,'', string);string = 'p y t h o n';print("原字符串:"+string);print("\n新字符串:"+remove(string)) ;
输出:
以上就是本篇文章的全部内容,希望能对大家的学习有所帮助。更多精彩内容大家可以关注相关教程栏目!!!
以上就是python如何删除字符串中所有空格的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product