本文摘自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中如何合并两个字典的示例分享
Python配置与opencv的使用详解
如何调试Python代码
Python爬虫是什么
Python怎么安装tensorflow
Python能做游戏吗
Python numpy怎么提取矩阵的指定行列
c#如何调用Python
Python中pow什么意思
Python之io多路复用之epoll
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » Python如何删除字符串中所有空格