![图片[1]-python怎么去去掉字符串中的空字符串-uusu优素-乐高,模型,3d打印,编程](http://uusucn.zbbe.cn/wp-content/uploads/2024/01/5eb644f041354451.jpg)
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));
运行结果如下:

© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END

















































暂无评论内容