You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Python变量输出,仅提取图片文件名?

提取图片URL中的文件名

你的代码目前输出完整的图片URL,要仅获取文件名(如99.jpg),可以通过以下两种简单方式修改:

方法1:字符串分割

利用URL的结构,通过split('/')分割字符串后取最后一个元素:

#imports
import requests
#setup
response = requests.get("https://randomfox.ca/floof/")
fox = response.json()
#code
print(fox['image'].split('/')[-1])

方法2:使用os.path模块(更健壮)

如果需要处理更复杂的URL路径,os.path.basename是更可靠的选择,它会自动提取路径的最后部分:

#imports
import requests
import os
#setup
response = requests.get("https://randomfox.ca/floof/")
fox = response.json()
#code
print(os.path.basename(fox['image']))

两种方法都能输出你需要的99.jpg这类文件名。

内容的提问来源于stack exchange,提问作者mmewtwosaysbye

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 16:47:32