[docs] have a question about "strip"

Julien Palard julien at palard.fr
Sat Jul 6 10:58:32 EDT 2019

Hi Robin,

It's not a question about the documentation, so I think you posted to the wrong mailing list, maybe tutor would be a better choice.

I don't know where you see a bug, the documentation for strip [1] contains:

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

in "ea".strip("ge") you're asking: "From the string 'ea', remove leading and trailing 'g's and 'e's", which results in "a", it looks correct to me.

The hard point to get may be the fact that strips takes a *set* of letters to strip, not a word to strip. If you want to strip words you can use re like this:

>>> re.sub("^hello|hello$", "", "hello world is hello")
' world is '

^hello meaning "hello at the beginning"
| means or
hello$ means "hello at the end"

So it reads like this: "hello at the beginning or hello at the end are replaced by the empty string". Note that the space are kept, we did *not* asked for them to be dropped (they can easily be drop by using strip agian.

Please not my "re" example is not perfect, it strips only once.

A more robust one could be:

>>> def wstrip(word, string):
...     return re.sub(f"^({re.escape(word)}\s?)*|(\s?{re.escape(word)})*$", "", string)
>>> wstrip("hello", "hello hello hello youpi hello hello")
>>> wstrip("hello", "hello hello hello hello hello")

But it's probably not foolproof, not well tested, and not that readable.

[1]: https://docs.python.org/3/library/stdtypes.html#str.strip

Julien Palard

‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐
On Saturday 6 July 2019 14:08, chinapython at yeah.net <chinapython at yeah.net> wrote:

> hi.all
>        I'm robin.come from china,I have a question about "strip":
>        version:Python 3.7.0
>         >>> a='ea'
>         >>> print([a.strip()])
>         ['ea']
>         >>> print([a.strip('page')])
>         ['']
>         >>> print([a.strip('ge')])
>         ['a']
>          is this a bug?
> ---------------------------------------------------------------
> chinapython at yeah.net
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/docs/attachments/20190706/98d54a4f/attachment-0001.html>

More information about the docs mailing list