Closed Shom770 closed 2 years ago
strip/strip-gotcha
When working with strip, lstrip, or rstrip, you might think that this would be the case:
strip
lstrip
rstrip
"Monty Python".rstrip(" Python") >>> "Monty"
While this seems intuitive, it would actually result in:
"Monty Python".rstrip(" Python") >>> "M"
as Python interprets the argument to these functions as a set of characters rather than a substring.
If you want to remove a prefix/suffix from a string, str.removeprefix and str.removesuffix are recommended and were added in 3.9.
str.removeprefix
str.removesuffix
"Monty Python".removesuffix(" Python") >>> "Monty"
See the documentation for str.removeprefix and str.removesuffix here
str.removeprefix
This is a useful tag. I was surprised by this myself once.
Merged in python-discord/bot#2000
Tag Name
strip/strip-gotcha
What kind of content should the tag include?
When working with
strip
,lstrip
, orrstrip
, you might think that this would be the case:While this seems intuitive, it would actually result in:
as Python interprets the argument to these functions as a set of characters rather than a substring.
If you want to remove a prefix/suffix from a string,
str.removeprefix
andstr.removesuffix
are recommended and were added in 3.9.See the documentation for
str.removeprefix
andstr.removesuffix
here