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

图片[1]-python中如何删除字符串中的空格-uusu优素-乐高,模型,3d打印,编程

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="88888888thisisstringexample....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="88888888thisisstringexample....wow!!!8888888";
printstr.rstrip('8');

输出结果如下:

this is string example….wow!!!

88888888this is string example….wow!!!

原文来自:https://www.py.cn
© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片快捷回复

    暂无评论内容