Python 删除字符串
来源:互联网 发布:淘宝网针织衫大外套 编辑:程序博客网 时间:2024/05/22 15:24
1、strip(),lstrip(),rstrip()方法,在没有参数时,分别能删除字符串开头或结尾、左边的、右边的空格,传入参数时,分别能删除字符串开头或结尾、左边的、右边的相关字符串。
>>> # Whitespace stripping>>> s = ' hello world \n'>>> s.strip()'hello world'>>> s.lstrip()'hello world \n'>>> s.rstrip()' hello world'>>>>>> # Character stripping>>> t = '-----hello====='>>> t.lstrip('-')'hello====='>>> t.strip('-=')'hello'>>>
2、若你想删除字符串中间的空格或者相关字符,可以用replace方法或者正则表达式。
>>> s.replace(' ', '')'helloworld'>>> import re>>> re.sub('\s+', ' ', s)'hello world'>>>
3、通常情况下你想将字符串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操作。
对于更高阶的strip,你可能需要使用 translate() 方法。
0 0
- Python 删除字符串
- python删除字符串
- python 删除字符串中的空格
- python--字符串操作(删除,替换)
- Python 字符串的删除和替换
- 删除字符串中的控制字符(python)
- Python 字符串,list排序,删除重复数据
- python--字符串操作(删除,替换)
- python 删除字符串中的连续空格只保留一个
- Python字符串方法详细介绍2_删除
- python--文件删除、判断目录存在、字符串替换
- python 删除字符串中指定字符&去掉空格
- python字符串操作,截取,拼接,替换,删除,比较,查找
- Python学习_我该如何删除字符串中的空白
- 删除字符串
- 字符串删除
- Python字符串
- Python 字符串
- UIScrollView
- [BZOJ4198][Noi2015]荷马史诗
- Algorithms—228.Summary Ranges
- 【线段树I:点修改+区间查询】hdu 1754 I Hate It
- MYSQL 日期函数
- Python 删除字符串
- CRC循环冗余校验码
- Express 2015 RC for Windows 10 安装
- 合唱队
- CDN--前端性能优化
- Python爬虫基础(一)--简单的url请求
- OC语言(二)
- 获取某个月的第一天和最后一天
- hdoj 1565 方格取数(1) 【状压DP 基础题目】