python删除字符串

  • 删除开头或者结尾的字符:strip()方法

    lstrip() 和rstrip()分别从左和从右执行删除操作。默认会删除空白字符

    $ python
    Python 3.5.2 (default, Sep 14 2017, 22:51:06) 
    [GCC 5.4.0 20160609] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> s = '  hey you '
    >>> s.strip()
    'hey you'
    >>> t = '--hey you--'
    >>> t.strip('-')
    'hey you'
    >>> t.rstrip('-')
    '--hey you'
    >>> t.lstrip('-')
    'hey you--'
    >>> 

  • 处理中间空格或者字符:replace()

    
    #!/usr/bin/python3                                                              
    
    
    # -*- coding: utf-8 -*-
    
    """
    
    # Author: EricRay
    
    
    # Created Time : 2017-11-28 15:33:43
    
    
    
    # File Name: anti_vowel.py
    
    
    # Description:剔除字符中的元音
    
    
    """
    def anti_vowel(text):
      vowel = 'aeiouAEIOU'
      for c in text:
          if c in vowel:
              text = text.replace(c, '') 
      return text
    
    print (anti_vowel(input("please input the text:")))
    
  • strip()与迭代操作结合:从文件中读取多行数据

    with open(filename) as f:
      lines = (line.strip() for line in f)#执行数据转换操作
      for line in lines:
          print(line)

    表达式 lines = (line.strip() for line in f) 执行数据转换操作。 这种方式非常高效,因为它不需要预先读取所有数据放到一个临时的列表中去。 它仅仅只是创建一个生成器,并且每次返回行之前会先执行 strip 操作

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值