小编给大家分享一下python去掉字符串中空字符串的方法,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!

python中去除字符串中空字符的方法:

1、使用replace()函数

我们可以使用replace()函数,把所有的空格(" ")替换为("")

defremove(string):returnstring.replace("","");string='HELLO!';print("原字符串:"+string);print("\n新字符串:"+remove(string));

输出:

2、使用split()函数+join()函数

split()函数会通过指定分隔符对字符串进行切片,返回分割后的字符串的所有单字符列表。然后,我们使用join()函数迭代连接这些字符。

defremove(string):return"".join(string.split());string='world';print("原字符串:"+string);print("\n新字符串:"+remove(string));

运行结果如下:

看完了这篇文章,相信你对python去掉字符串中空字符串的方法有了一定的了解,想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!