python - 如何通过python格式化url中的字符串?
问题描述
我可以用 1 个变量格式化链接(link1),但是当我想用 2 个变量格式化链接(link2)时,它会引发错误( ValueError: unsupported format character 'A' (0x41) at index 94)应该是 link2要: https://widget.s24.com/applications/1e082c83/widgets/422/products?searchTerm=Topper&origin=https%3A%2F%2Fwww.real.de%2Fproduct%2F324093002%2F
有什么解决办法吗?
i = 324093002
b = "Topper"
link_product = 'https://www.real.de/product/%s/'
link_keyword = 'https://widget.s24.com/applications/1e082c83/widgets/422/products?searchTerm=*%s*&origin=https%3A%2F%2Fwww.real.de%2Fproduct%2F*%s*%2F'
link1 = link_product %i
link2 = link_keyword % (i, b)
解决方案
Char%
在字符串格式中具有特殊含义-例如%s
,%i
等-并且您有%3A
%2F
不正确的格式。您必须使用%%
通知 Python 您需要普通字符%
- %%3A
%%2F
i = 324093002
b = "Topper"
link_keyword = 'https://widget.s24.com/applications/1e082c83/widgets/422/products?searchTerm=*%s*&origin=https%%3A%%2F%%2Fwww.real.de%%2Fproduct%%2F*%s*%%2F'
link2 = link_keyword % (i, b)
print(link2)