[英]how do I modify a url that I pick at random in python
我有一個應用程序,它將顯示來自reddit的圖像。 一些圖片來這樣http://imgur.com/Cuv9oau ,當我需要讓他們看起來像這樣http://i.imgur.com/Cuv9oau.jpg 。 只需在開頭添加(i),在末尾添加(.jpg)。
您可以使用字符串替換:
s = "http://imgur.com/Cuv9oau"
s = s.replace("//imgur", "//i.imgur")+(".jpg" if not s.endswith(".jpg") else "")
將s設置為:
'http://i.imgur.com/Cuv9oau.jpg'
此功能應該可以滿足您的需求。 我擴展了@ jh314的響應,並簡化了代碼,並檢查了該URL是否以http://imgur.com
開頭 ,因為該代碼會引起其他URL的問題,例如我所包含的google搜索。 它還僅替換了可能導致問題的一審。
def fixImgurLinks(url):
if url.lower().startswith("http://imgur.com"):
url = url.replace("http://imgur", "http://i.imgur",1) # Only replace the first instance.
if not url.endswith(".jpg"):
url +=".jpg"
return url
for u in ["http://imgur.com/Cuv9oau","http://www.google.com/search?q=http://imgur"]:
print fixImgurLinks(u)
給出:
>>> http://i.imgur.com/Cuv9oau.jpg
>>> http://www.google.com/search?q=http://imgur
您應該使用Python的正則表達式放置i
。 至於.jpg
您可以附加它 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.