如何在python中转义url编码的管道(|)符号

2024-06-01 02:47:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python中遇到了urllib.url_encode的问题。Bets解释了一些代码:

>>> from urllib import urlencode
>>> params = {'p' : '1 2 3 4 5&6', 'l' : 'ab|cd|ef'}
>>> urlencode(params)
'p=1+2+3+4+5%266&l=ab%7Ccd%7Cef'

我想把管道(“|”)保留在to l参数中。你能告诉我怎么做吗?

结果应该是

'p=1+2+3+4+5%266&l=ab|cd|ef'

PS:我不想手动组合URL,但是要使用urlencode。

谢谢 -帕特


Tags: to代码fromimporturl参数管道ab
2条回答

Convert a mapping object or a sequence of two-element tuples to a “percent-encoded” string[...]

urlencode()方法按预期工作。如果要阻止编码,则可以先对整个对象进行编码,然后用管道替换编码的字符。

>>> u = urlencode(params)
>>> u.replace('%7C', '|')
'p=1+2+3+4+5%266&l=ab|cd|ef'  

在Python 3中更简单:

urllib.parse.urlencode(params, safe='|')

相关问题 更多 >