str.strip() removes more than you asked
str.strip() removes more than you asked in Python means strip("https://") does not remove that word. It removes any of the characters h, t, p, s, : and / from both ends until it meets one that is not in the set.
How do I fix str.strip() removes more than you asked?
In Python, str.strip("https://") treats its argument as a set of characters, not a word. It removes any of h, t, p, s, : and / from both ends, so "https://shop.com" becomes "op.com". Use url.removeprefix("https://") or name.removesuffix(".txt") instead, available from Python 3.9.
- 1. strip() with an argumentAny strip("..."), lstrip("...") or rstrip("...") with a multi-character string is a likely culprit.
- 2. Use removeprefix/removesuffixThese remove exact text once and only if it is there. Plain strip() is fine for whitespace.
- 3. File namesFor extensions, pathlib.Path(name).stem and .suffix handle names like test.txt correctly.
What does str.strip() removes more than you asked mean?
The argument to strip(), lstrip() and rstrip() is a set of single characters, not a substring. So "https://shop.com".strip("https://") keeps going past the prefix and eats the s and h of shop. Python 3.9 added removeprefix() and removesuffix() for exact text.
Why does str.strip() removes more than you asked happen?
1. Removing a URL prefix
The domain's first letters may be in the character set.
Breaks
url.strip("https://") # 'op.com'Works
url.removeprefix("https://") # 'shop.com'2. Removing a file extension
Letters of the name that are also in the extension disappear.
Breaks
"data.txt".rstrip(".txt") # 'data' by luck; 'test.txt' -> 'tes'Works
"test.txt".removesuffix(".txt") # 'test'How to find it in your own code
Use strip() with no argument for whitespace, and removeprefix()/removesuffix() for exact text. For file names, pathlib.Path(name).stem and .suffix are more robust still.
Try it: fix this bug
mediumdomain_of("https://shop.com") returns "op.com". domain_of("https://example.org") works.
def domain_of(url):
return url.strip("https://")Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.