Tilak Maddy Tilak Maddy -4 years ago 128
Python Question

The best practice to count characters from back in Python

I have a Python string like this:

url = "https://github.com/websanova/boilerplate/archive/master.zip"


And to extract the documentation URL, I will have to remove 18 characters from back which corresponds to
archive/master.zip
so that I get this
https://github.com/websanova/boilerplate/


So I did this:

documentation = url[:len(url)-18]


But something is telling me that's not the right way. I would like to know which is the best practice.

And .. I am using Py-V3.x

Answer Source

url[:-18] is sufficient. Negative indexes start at the len(str) automatically:

>>> url = "https://github.com/websanova/boilerplate/archive/master.zip"
>>> url[:-18]
'https://github.com/websanova/boilerplate/'

That being said, I wouldn't recommend using a set value... instead, I'd suggest something like:

url[:url.rfind('/', 0, url.rfind('/')) + 1]

which will strip off the filename and one folder, regardless of the length of each string:

url[:                                 + 1]  # slice the string, ending at
     url.rfind('/', 0,              )  # the last occurrence of / in the substring ending
                      url.rfind('/')  # on the last / (so exluding it)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download