[英]how do I modify a url that I pick at random in python
I have an app that will show images from reddit. 我有一个应用程序,它将显示来自reddit的图像。 Some images come like this http://imgur.com/Cuv9oau , when I need to make them look like this http://i.imgur.com/Cuv9oau.jpg .
一些图片来这样http://imgur.com/Cuv9oau ,当我需要让他们看起来像这样http://i.imgur.com/Cuv9oau.jpg 。 Just add an (i) at the beginning and (.jpg) at the end.
只需在开头添加(i),在末尾添加(.jpg)。
You can use a string replace: 您可以使用字符串替换:
s = "http://imgur.com/Cuv9oau"
s = s.replace("//imgur", "//i.imgur")+(".jpg" if not s.endswith(".jpg") else "")
This sets s to: 将s设置为:
'http://i.imgur.com/Cuv9oau.jpg'
This function should do what you need. 此功能应该可以满足您的需求。 I expanded on @jh314's response and made the code a little less compact and checked that the url started with
http://imgur.com
as that code would cause issues with other URLs, like the google search I included. 我扩展了@ jh314的响应,并简化了代码,并检查了该URL是否以
http://imgur.com
开头 ,因为该代码会引起其他URL的问题,例如我所包含的google搜索。 It also only replaces the first instance, which could causes issues. 它还仅替换了可能导致问题的一审。
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)
Gives: 给出:
>>> http://i.imgur.com/Cuv9oau.jpg
>>> http://www.google.com/search?q=http://imgur
You should use Python's regular expressions to place the i
. 您应该使用Python的正则表达式放置
i
。 As for the .jpg
you can just append it . 至于
.jpg
您可以附加它 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.