发布时间:2022-06-16 09:42:34 人气:319 作者:多测师
python中去除字符串中空字符的方法:
1、使用replace()函数
我们可以使用replace()函数,把所有的空格(" ")替换为("")
def remove(string):
return string.replace(" ", "");
string = ' H E L L O ! ';
print("原字符串:"+string) ;
print("\n新字符串:"+remove(string)) ;
2、使用split()函数+join()函数
split()函数会通过指定分隔符对字符串进行切片,返回分割后的字符串的所有单字符列表。然后,我们使用join()函数迭代连接这些字符。
def remove(string):
return "".join(string.split());
string = 'w o r l d ';
print("原字符串:"+string) ;
print("\n新字符串:"+remove(string)) ;
以上内容为大家介绍了python怎么去去掉字符串中的空字符串,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注多测师。https://www.e70w.com/xwzx/