当前位置: 首页 > 图灵资讯 > 行业资讯> python中如何删除字符串中的空格

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中如何删除字符串中的空格

python中如何删除字符串中的空格

2026-04-15
python中如何数出字符串的字符个数

python中如何数出字符串的字符个数

2026-04-15
python中sort是什么意思

python中sort是什么意思

2026-04-15
python中setuptools是什么

python中setuptools是什么

2026-04-15
python中r作用是什么?

python中r作用是什么?

2026-04-15
Python中sys属于什么库

Python中sys属于什么库

2026-04-14