python怎么去去掉字符串中的空字符串
发布时间:2026-04-19 15:42:53

在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视频教程栏目,了解更多Python知识。
