简体   繁体   English

PYTHON:如何抓取字符串的特定部分?

[英]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.我有以下字符串:“https://www.instagram.com/paula.mtzm/”我想将用户“paula.mtzm”放到一个变量中。 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/”,然后删除最后一个字符“/”?

"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实际上,它使用分隔符.com/将字符串拆分为一个列表,获取该列表的最后一项( "paula.mtzm/" ),最后删除所有剩余的/ 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.字符串在 Python 中就像列表一样被索引。 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.因此,对于您的特定问题,您可以让代码搜索第 3 个正斜杠并在此之后获取所有内容。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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