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