Python strip方法

2024-05-22 15:20:25 发布

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

今天在python终端,我试着

a = "serviceCheck_postmaster"
a.strip("serviceCheck_")

但是我得到的不是"postmaster",而是"postmast"

是什么原因造成的?我怎样才能得到"postmaster"作为输出?


Tags: 终端checkservice原因strippostmastpostmaster
3条回答

如果你仔细看一下剥离功能的帮助 上面写着:

Help on built-in function strip:

strip(...)
    S.strip([chars]) -> string or unicode

    Return a copy of the string S with leading and trailing
    whitespace removed.
    If chars is given and not None, remove characters in chars instead.
    If chars is unicode, S will be converted to unicode before stripping

它将删除所有前导和尾随字符以及空白。在你的例子中,字符集是

s, e, r, v, i, c, C, h, k and _

你可以通过这样的方式找到邮局局长

a = "serviceCheck_postmaster"
print a.split("_")[1]

Martijn对would的回答的另一种选择是使用str.replace()

>>> a = "serviceCheck_postmaster"
>>> a.replace('serviceCheck_','')
'postmaster'

你误解了.strip()的作用。它将删除传递的字符串中的任何字符。从^{} documentation

The chars argument is a string specifying the set of characters to be removed.

强调我的;单词set那里是至关重要的。

因为chars被视为一个集合,.strip()将从输入字符串的开头和结尾删除所有servicChk_字符。因此输入字符串的结束中的er字符也被删除;这些字符是集合的一部分。

要从开头或结尾删除字符串,请改用切片:

if a.startswith('serviceCheck_'):
    a = a[len('serviceCheck_'):]

相关问题 更多 >

    热门问题