簡體   English   中英

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

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM