189 8069 5689

python中删除字符串中空格的方法

这篇文章将为大家详细讲解有关python中删除字符串中空格的方法,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

创新互联建站专注于企业全网营销推广、网站重做改版、荔湾网站定制设计、自适应品牌网站建设、H5建站购物商城网站建设、集团公司官网建设、成都外贸网站建设公司、高端网站制作、响应式网页设计等建站业务,价格优惠性价比高,为荔湾等各大城市提供网站开发制作服务。

python中删除字符串中空格的方法:

1、使用replace()函数,把所有的空格(" ")替换为("")

def remove(string): 
    return string.replace(" ", "");
     
string = ' H  E  L  L  O  ! ';
print("原字符串:"+string) ;
print("\n新字符串:"+remove(string)) ;

输出结果:

原字符串: H  E  L  L  O  !

新字符串:HELLO!

2、使用lstrip()函数删除字符串左边空格

lstrip()方法语法:

str.lstrip([chars])

示例:

#!/usr/bin/python

str = "     this is string example....wow!!!     ";
print str.lstrip();
str = "88888888this is string example....wow!!!8888888";
print str.lstrip('8');

输出结果:

this is string example....wow!!!

this is string example....wow!!!8888888

3、使用rstrip()函数删除字符串末尾空格

rstrip()方法语法:

str.rstrip([chars])

示例:

#!/usr/bin/python

str = "     this is string example....wow!!!     ";
print str.rstrip();
str = "88888888this is string example....wow!!!8888888";
print str.rstrip('8');

输出结果如下:

     this is string example....wow!!!

88888888this is string example....wow!!!

关于python中删除字符串中空格的方法就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。


网页标题:python中删除字符串中空格的方法
分享URL:http://cdxtjz.cn/article/psiphj.html

其他资讯