如何从字符串中删除正斜杠

2024-05-29 07:45:58 发布

您现在位置:Python中文网/ 问答频道 /正文

Python 2.7.3 (default, Apr 20 2012, 22:44:07) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.  

>>> s = "www.example.com/help"
>>> s.strip('/')
>>> 'www.example.com/help'    #expected 'www.example.comhelp'
>>> t = "/blah/blah/"
>>> t.strip('/')
>>> 'blah/blah'    #expected 'blahblah'
>>> s.strip('w.')
>>> 'example.com/help'    #expected 'examplecom/help'
>>> f = 'www.example.com'
>>> f.strip('.')
>>> 'www.example.com'    #expected 'wwwexamplecom'
>>> f.strip('comw.')
>>> 'example'    #as expected

有人能解释一下为什么str.strip看起来不像承诺的那样工作吗?

从文档中:

str.strip([chars])

Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:


Tags: orofthecomstringexamplewwwhelp
3条回答

strip只删除前导和尾随字符。

我建议使用:

s.replace('/', '')

相反。

另一种方法

    In [19]: s = 'abc.com/abs'
    In [29]: exclude = '/'
    In [31]: s = ''.join(ch for ch in s if ch not in exclude)
    In [32]: s
    Out[32]: 'abc.comabs'

str.strip([chars])

Return a copy of the string with the leading and trailing characters removed.

使用此选项可在任何位置替换字符串:

s.replace('/', '')

相关问题 更多 >

    热门问题