本文摘自php中文网,作者青灯夜游,侵删。
在Python中删除字符串中所有空格有:使用replace()函数、使用split()函数+join()函数、使用Python正则表达式。下面本篇文章就来具体介绍一下这些方法,希望对大家有所帮助。【相关视频教程推荐:Python教程】
使用replace()函数
我们可以使用replace()函数,把所有的空格(" ")替换为("")
1 2 3 4 5 6 | def remove(string):
return string.replace( " " , "" );
string = ' H E L L O ! ' ;
print ( "原字符串:" +string) ;
print ( "\n新字符串:" +remove(string)) ;
|
输出:

使用split()函数+join()函数
split()函数会通过指定分隔符对字符串进行切片,返回分割后的字符串的所有单字符列表。然后,我们使用join()函数迭代连接这些字符。
1 2 3 4 5 6 | def remove(string):
return "" .join(string.split());
string = 'w o r l d ' ;
print ( "原字符串:" +string) ;
print ( "\n新字符串:" +remove(string)) ;
|
输出:
阅读剩余部分
相关阅读 >>
Python如何使用cx_oracle调用oracle存储过程的示例
Python中一些常用模块的介绍
如何用Python搭建匿名代理池?搭建匿名代理池的方法
怎么看Python安装了哪些库
怎么用Python打开文件
Python可以做手游么
Python中psutil库的使用介绍(详细)
Python引用计数与弱引用的简单了解(附实例)
Python怎样求得最大公约数
map在Python中什么意思
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » Python如何删除字符串中所有空格