如何在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
相关产品推荐
相关产品推荐

