[英]PYTHON: How do I grab a specific part of a string?
我有以下字符串:“https://www.instagram.com/paula.mtzm/”我想将用户“paula.mtzm”放到一个变量中。 有人知道怎么做吗 ? 也许您可以以某种方式删除字符串的一部分,例如“https://www.instagram.com/”,然后删除最后一个字符“/”?
"https://www.instagram.com/paula.mtzm/".split(".com/")[-1].replace("/", "")
这应该做你想做的。 实际上,它使用分隔符.com/
将字符串拆分为一个列表,获取该列表的最后一项( "paula.mtzm/"
),最后删除所有剩余的/
s
我不确定您的用例有多具体,所以我不知道这通常有多合适。
这实际上很简单:
字符串在 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
因此,对于您的特定问题,您可以让代码搜索第 3 个正斜杠并在此之后获取所有内容。
如果你总是知道网址,你可以在地址的末尾和用户开始的地方开始你的索引:
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.