您好,欢迎来到花图问答。
搜索
您的当前位置:首页python中如何删除字符串中的空格

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

来源:花图问答

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知识请关注栏目。

Copyright © 2019- huatuowenda.com 版权所有 湘ICP备2023022495号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务