后浪云Python教程:python怎么去去掉字符串中的空字符串
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)) ;
运行结果如下:
版权声明:
作者:后浪云
链接:https://www.idc.net/help/182541/
文章版权归作者所有,未经允许请勿转载。
THE END