python中如何删除字符串中的空格
发布时间:2026-04-15 15:40:17

在python中删除字符串中空格的方法:
1、使用replace()函数将所有空间(" ")替换为("")
defremove(string):
returnstring.replace("","");
string='HELLO!';
print("原字符串:"+string);
print("\n新字符串:"+remove(string));输出结果:
原字符串: H E L L O ! 新字符串:HELLO!
2、使用lstrip()函数删除字符串左侧空间
lstrip()方法语法:
str.lstrip([chars])
示例:
#!/usr/bin/python
str="thisisstringexample...wow!!!";
printstr.lstrip();
str="88888888thisstringexaple...wow!!!8888888";
printstr.lstrip('8');输出结果:
this is string example...wow!!!
this is string example...wow!!!8888888
3、使用rstrip()函数删除字符串末尾空间
rstrip()方法语法:
str.rstrip([chars])
示例:
#!/usr/bin/python
str="thisisstringexample...wow!!!";
printstr.rstrip();
str="88888888thisstringexaple...wow!!!8888888";
printstr.rstrip('8');输出结果如下:
this is string example...wow!!!
88888888this is string example...wow!!!
请关注Python视频教程栏目,了解更多Python知识。
下一篇 python中如何对数字排序
