删除开头或者结尾的字符: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
操作
python删除字符串
最新推荐文章于 2024-05-13 15:27:19 发布