简体   繁体   中英

PYTHON: How do I grab a specific part of a string?

I have the following string: "https://www.instagram.com/paula.mtzm/" I want to put the user "paula.mtzm" to a variable. Anyone know how to do this ? Maybe you can somehow delete a part of the string like "https://www.instagram.com/" and then delete the last character "/" ?

"https://www.instagram.com/paula.mtzm/".split(".com/")[-1].replace("/", "")

This should do what you want. Effectively it splits the string into a list using the separator .com/ , gets the last item of that list ( "paula.mtzm/" ), and finally removes any remaining / s

I'm not sure how specific your use-case is so I don't know how suitable this is in general.

This is actually pretty easy:

Strings are indexed in Python just like a list. So:

string = "potato"
print string[0] #this will print "p" to the console
#we can 'slice' in the index too
print string[0:3] #this will print "pot" to the console

So for your specific problem you could have your code search for the 3rd forward slash and grab everything after that.

If you always know the web address you can just start your index at the end of the address and where the user begins:

string = "https://www.instagram.com/paula.mtzm/"
string_index = 26 # the 'p' in paula begins here
user_name = string[string_index:string.len]
print user_name #outputs paula.mtzm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM