【问题标题】:Python: encode special characterPython:编码特殊字符
【发布时间】:2013-07-18 11:45:32
【问题描述】:

我正在尝试将包含“-”(减号)符号的字符串编码为 iso8859-15,它会按原样返回字符串。 例如:

str="abc-def"

预期输出是

abc%2Ddef

有没有办法做到这一点?对不起,如果我的问题是错误的。

【问题讨论】:

  • 这不是 Latin-1 编码。你可能想复习一下是什么编码。 :-)
  • 不要命名变量str;掩盖内置类型。

标签: python special-characters encode


【解决方案1】:

您的输出示例表明您正在寻找 url 编码,而不是 Latin-1。

urllib.quote()urllib.quote_plus() 函数可用于进行此类引用,但 - 字符不需要需要引用且不会被引用:

使用 %xx 转义符替换 string 中的特殊字符。字母、数字和字符 '_.-' 从不被引用。

演示:

>>> from urllib import quote
>>> quote('abc-def')
'abc-def'
>>> quote('some data that needs quoting!')
'some%20data%20that%20needs%20quoting%21'

如果您使用的是 Python 3,quotequote_plus 函数可以在 urllib.parse module 中找到。

【讨论】:

    【解决方案2】:

    是的。

    from urllib.parse import quote
    st = "abc-def"
    encoded = quote(st)
    

    【讨论】:

    • 作为记录,urllib.parse 是一个 Python 3 模块。在 Python 2 中,quote 位于 urllib 中(无子模块)。
    猜你喜欢
    • 2016-10-19
    • 2013-06-07
    • 1970-01-01
    • 2012-12-09
    • 2014-09-17
    • 1970-01-01
    • 1970-01-01
    • 2012-03-18
    相关资源
    最近更新 更多