EASY Python Mistake!!
Here’s a Python mistake that’s very easy to make
Let’s say we have a list of domain names and we want to cycle through them and remove the www.
at the beginning of each one.
links = [
"www.amazon.com",
"www.wikipedia.org",
"www.reddit.com",
]
One way you might think to do this is to say
for link and links:
print(link.lstrip("www."))
lstrip()
essentially strips www.
characters from the left side of the string
The problem is when we run this you’ll see that the w
in www.wikipedia.org
is gone
It’s because the input for lstrip()
is actually a list of characters to remove.
It’s not looking to remove the substring www.
so we could say w.
and it would do the same thing.
It’s looking for all the W
’s and .
from the left side and removing them until it hits a character that’s not on this list.
Instead, we should use the removeprefix()
method with an input of www.
for link and links:
print(link.removeprefix("www."))
This method actually looks for the first instance of this substring from the left side and removes it