• 技术文章 >常见问题 >Python常见问题

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

    yangyang2020-05-11 11:36:26原创4409

    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视频教程栏目。

    专题推荐:python
    上一篇:python中如何对数字排序 下一篇:python中如何数出字符串的字符个数

    相关文章推荐

    • python怎么查内建函数• python怎么判断一个数是几位数• 用python写好的程序如何在别处用• python中如何计算矩阵的行数?

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网