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

时间:2020-09-13 16:47:32

标签: python

我有以下字符串:“ https://www.instagram.com/paula.mtzm/” 我想将用户“ paula.mtzm”放入一个变量。 有人知道怎么做吗 ?也许您可以以某种方式删除字符串的一部分,例如“ https://www.instagram.com/”,然后删除最后一个字符“ /”?

2 个答案:

答案 0 :(得分:1)

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

这应该做您想要的。有效地使用分隔符.com/将字符串拆分为一个列表,获取列表的最后一项("paula.mtzm/"),最后删除所有剩余的/

我不确定您的用例有多具体,所以我不知道这通常是多么合适。

答案 1 :(得分:1)

这实际上很简单:

在Python中,字符串像列表一样被索引。所以:

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

因此,对于您的特定问题,您可以让代码搜索第三个 正斜杠,然后抓住所有东西。

如果您始终知道网址,则只需在索引末尾开始索引 地址和用户开始的位置:

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