在Python中将十六进制字符串转换为百分比编码字符串
我有一根绳子。它看起来像 s = 'e6b693e6a0abe699ab'
。
我想在每对字符前面放置一个百分号,因此 percentEncode(s) == '%e6%b6%93%e6%a0%ab%e6%99%ab'
。
编写 percentEncode(s)
的好方法是什么?
(请注意,我不关心非保留字符不会转换为 ASCII .)
我可以想出一些冗长的方法来做到这一点,但我想要一些漂亮而简单的方法,虽然我对 Python 相当陌生,但如果 Python 不能很好地做到这一点,我会感到惊讶。
I have a string. It looks like s = 'e6b693e6a0abe699ab'
.
I want to put a percent sign in front of every pair of characters, so percentEncode(s) == '%e6%b6%93%e6%a0%ab%e6%99%ab'
.
What's a good way of writing percentEncode(s)
?
(Note, I don't care that unreserved characters aren't converted into ASCII.)
I can think of big verbose ways of doing this, but I want something nice and simple, and while I'm fairly new to Python, I'd be suprised if Python can't do this nicely.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
或者使用重新
Or using re
如果您手动进行 URL 编码,您可能需要阅读此 博客文章。它解释了如何使用标准库的
urllib
模块来执行此操作quote_plus
函数。On the off chance that you are doing URL-encoding manually, you might want to read this blog post. It explains how to do this using the standard library's
urllib
module'squote_plus
function.哦,你的意思是:
虽然可能如果你这样做是为了 url 转义或类似的事情,那么有一个库函数更适合你的使用。
编辑添加——因为每个人都喜欢可爱的 itertools 解决方案:
Oh, you mean:
Though probably if you're doing this for url escaping or some such, there's a library function more appropriate to your use.
Edited to add -- since everyone loves a cute itertools solution:
使用正则表达式达到
/([0-9a-f]{2})/ig
的效果并替换为%\1
use a Regex to the effect of
/([0-9a-f]{2})/ig
and replace with%\1
只是为了学术。
尝试使用尽可能多的迭代器。
感谢 @tcarobruce 提醒重用字符串 iter。
Just to be academic.
Trying to use as many iterators as possible.
Thanks to @tcarobruce for the reminder to reuse the string iter.
根据您在最初问题中的评论,如果从初始字符串
initial_s
开始,然后将其编码为十六进制,则结果可以为:Based on a comment of yours in the initial question, if starting from the initial string
initial_s
before its encoding into hex, you can have the result as: