String.strip function has weird result

Hi All,
I got weird while running string.strip function. I strip out ‘.git’ from 2 strings (‘abcdef’ and ‘abcdefi’) but the results are the same.

Here is what I got when running from shell.

Python 3.8.0 (default, Nov 14 2019, 22:29:45)
[GCC 5.4.0 20160609] on linux
Type “help”, “copyright”, “credits” or “license” for more information.


It is match with the result I run on local PC with Python 3.7.3 shell.
Thanks in advance for your help.

This is the expected behavior. Strip will strip out of the string all the characters that you provide. You provided ., g, i, and t. All those characters got stripped out in both examples.

1 Like

From the documentation (also available from the REPL with help(str.strip):

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.

So a_string.strip('.git') would remove all leading trailing . g i and t from the a_string. The result is therefore expected.

The simplest way to remove a .git suffix would be:

def remove_trailing_dot_git(s):
    if s[-4:] == '.git':
        s = s[:-4]
    return s

You may also find one of str.rsplit(), str.rpartition(), or os.path.splitext() useful.


If working with path-like strings, consider pathlib:

# 'abcdef'

# 'abcdefi'

or as mentioned by @uranusjr os.path :

# 'abcdef'

# 'abcdefi'
1 Like

Thank you so much all. So I misunderstand the strip function.

1 Like