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

Python如何对URL字符串内的数值做乘法以生成分页链接

问题原因

字符串格式化操作只会替换占位符、拼接字符串,不会自动计算字符串内部的算术表达式。你调用eval时传入的是完整URL字符串,不属于合法Python语法,因此触发语法报错。

基础修复代码

如果你已经明确步长为25、URL前缀固定,直接把算术计算放在字符串格式化之前完成即可:

# 抽离公共参数
base_url_template = "https://www.example.com?id=s-{}"
step = 25
page_total = 5

for i in range(1, page_total + 1):
    current_value = step * i
    # 按要求输出带双引号的URL
    print(f'"{base_url_template.format(current_value)}"')

通用适配版本

如果需要从给定的原始链接自动提取步长、适配不同前缀的URL,可以加一步正则提取逻辑:

import re

origin_link = "https://www.example.com?id=s-25"
# 提取s-后面的数字作为步长
step = int(re.search(r'id=s-(\d+)', origin_link).group(1))
# 提取公共URL前缀
base_url_template = origin_link.rsplit('-', 1)[0] + "-{}"
page_total = 5

for i in range(1, page_total + 1):
    print(f'"{base_url_template.format(step * i)}"')

最终输出和需求完全一致:

"https://www.example.com?id=s-25"
"https://www.example.com?id=s-50"
"https://www.example.com?id=s-75"
"https://www.example.com?id=s-100"
"https://www.example.com?id=s-125"

内容的提问来源于stack exchange,提问作者Neo-coder

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 18:18:03