开发者社区 问答 正文

删除字符串中不需要的字符

你想去掉文本字符串开头,结尾或者中间不想要的字符,比如空白。

展开
收起
哦哦喔 2020-04-16 19:19:25 1111 分享 版权
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'
    >>>
    
    2020-04-16 19:19:37
    赞同 展开评论
问答地址: