【问题标题】:Why Python adds extra characters in string?为什么 Python 在字符串中添加额外的字符?
【发布时间】:2020-11-25 05:26:12
【问题描述】:

我只需要更改 url 的一小部分,但 Python 添加了额外的东西,特别是这个:'amp;' 位,这会弄乱 url 地址生成错误,因为 url 没有存在! 示例:

specialinfo = str(42)
my_url = 'https://www.justexample.com/thingshere/morestuff/ordinaryurlthing?mybit=' + specialinfo + '&endofmyurlbits'
print(my_url)

我得到的是:

https://www.justexample.com/thingshere/morestuff/ordinaryurlthing?mybit=42&endofmyurlbits

而不是我所期望的:

https://www.justexample.com/thingshere/morestuff/ordinaryurlthing?mybit=42&endofmyurlbits

如果我排除 'https:' 位,它会起作用!示例:

specialinfo = str(42)
my_url = 'www.justexample.com/thingshere/morestuff/ordinaryurlthing?mybit=' + specialinfo + '&endofmyurlbits'
print(my_url)

现在我明白了:

www.justexample.com/thingshere/morestuff/ordinaryurlthing?mybit=42&endofmyurlbits

我正在使用:

with urllib.request.urlopen('https://'+my_url) as remote:
    data = remote.read()

而且它正在工作。然而,问题依然存在!为什么在上面提到的字符串中添加'https://'?

ps.:我在 Windows 10 中使用 Python 3 和 Jupyterlab。

【问题讨论】:

    标签: python string url


    【解决方案1】:

    试试这个:

    import html
    html.unescape('https://www.justexample.com/thingshere/morestuff/ordinaryurlthing?mybit=42&endofmyurlbits')
    

    这应该可行。 发生这种情况是因为 HTML 仅接受 utf-8 并尝试转换所有非 utf-8 字符。您可以通过应用我刚刚展示的内容来避免这种情况。

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2011-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-02
      • 1970-01-01
      • 1970-01-01
      • 2018-08-30
      • 1970-01-01
      相关资源
      最近更新 更多