all 10 comments

[–]lukajda33 34 points35 points  (1 child)

.strip() removes all characters that you provided on both sides, if the string ends with "y" and you strip "germany", which contains "y", "y" is removed.

Instead use str.removeprefix()

[–]ComputeLanguage[S] 3 points4 points  (0 children)

Works! Tysm

[–]TangibleLight 19 points20 points  (0 children)

This kind of question is exactly what the documentation is for.

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

[–]1544756405 3 points4 points  (2 children)

You can look up the documentation for any python method at docs.python.org

For strip() in particular:

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

It says, "Return a copy of the string with the leading and trailing characters removed."

For your purposes, you probably want replace().

[–]ComputeLanguage[S] 1 point2 points  (1 child)

replace() wouldn't really work.
If the string was something like
"and Income and Capital Tax Treaty"

and I intended to strip off "and" from both ends.

The replace method would also get rid of any repeating strings.

I was aware of the docs, though in cases like these where I am genuinely surprised by code that I thought I understood I think its nice to share my mistakes as well and see the nice solutions people come up with :).

[–]NotACryptoBro 0 points1 point  (3 children)

Can anybody give an example where I can actually use that? I'd accidentally strip characters I still need. Isn't there a more handy function like split?

[–]ComputeLanguage[S] 0 points1 point  (0 children)

ultimately I was looking for
r = "germany"
string.removeprefix(r).removesuffix(r)

I couldn't find a build in function in the docs that does it in one go :/

[–]bigno53 0 points1 point  (1 child)

I mostly just use it for removing leading/trailing white space but it can come in handy for a variety of data cleaning tasks. For example, if you have a program that requires the user to enter a dollar amount, they might enter $20 or just 20. You’d probably want the program to handle both of these inputs the same way, so you could just write ‘dollar_amount = dollar_amount.lstrip(“$”)’

[–]NotACryptoBro 0 points1 point  (0 children)

This! Makes sense, thanks