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

如何在Python中为URL添加参数?附JavaScript实现示例

Python实现Telegram API URL参数拼接方案

当然可以在Python里实现类似的功能,给你几种常用且实用的方法:

方法1:f-string直接拼接(和JS模板字符串逻辑最接近)

这种方式和你JS里的模板字符串用法几乎一致,直接在字符串中嵌入变量:

user_id = '1234567890'
chat_ids = ['@test1', '@test2']

# 遍历每个chat_id生成完整URL
for chat_id in chat_ids:
    url = f"https://api.telegram.org/bot1234567890/banChatMember?chat_id={chat_id}&user_id={user_id}"
    print(url)

方法2:用urllib.parse.urlencode规范编码参数

如果参数里包含特殊字符(比如空格、&等),直接拼接可能会出问题,用urlencode能自动处理URL编码,更稳妥:

from urllib.parse import urlencode

user_id = '1234567890'
chat_ids = ['@test1', '@test2']
base_url = "https://api.telegram.org/bot1234567890/banChatMember"

for chat_id in chat_ids:
    params = {
        'chat_id': chat_id,
        'user_id': user_id
    }
    # 拼接基础URL和编码后的参数
    url = f"{base_url}?{urlencode(params)}"
    print(url)

方法3:用requests库直接传参(调用API更便捷)

如果你的最终目的是调用Telegram API,用requests库可以省去手动拼接URL的步骤,直接传参即可:

import requests

user_id = '1234567890'
chat_ids = ['@test1', '@test2']
base_url = "https://api.telegram.org/bot1234567890/banChatMember"

for chat_id in chat_ids:
    # requests会自动拼接URL并编码参数
    response = requests.get(base_url, params={'chat_id': chat_id, 'user_id': user_id})
    # 可以直接获取API返回的JSON数据
    print(response.json())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 18:04:59