【问题标题】:Python 3.6 urllib why line starts with bPython 3.6 urllib 为什么行以 b 开头
【发布时间】:2017-09-27 21:41:03
【问题描述】:

我正在使用 python 3,但不明白为什么输出的每个行首都有 b。我认为python 2不是这种情况。为什么会这样以及如何删除它?谢谢

import urllib
# fhand = urllib.urlopen('http://www.py4inf.com/code/romeo.txt') in Python 2
fhand = urllib.request.urlopen('http://www.py4inf.com/code/romeo.txt')
for line in fhand:
    print(line.strip())

输出看起来像这样

b'But soft what light through yonder window breaks'
b'It is the east and Juliet is the sun'
b'Arise fair sun and kill the envious moon'
b'Who is already sick and pale with grief'

【问题讨论】:

标签: python-3.x request urllib urlopen


【解决方案1】:

我知道这个问题一年多以前就已经回答过了,我找到了一个简单的答案。我只是在我的代码行中添加了decode()

def fetch_words():
    with urlopen(url) as story:
        story_words = []
        for line in story:
            line_words = line.decode('utf-8').split()
            for word in line_words:
                story_words.append(word)

        for word in story_words:
            print(word)

这有效并从每行的开头删除了 b。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-29
    • 2011-09-06
    • 1970-01-01
    • 2020-04-25
    • 2017-11-28
    • 2019-04-10
    • 2010-11-16
    • 2011-03-05
    相关资源
    最近更新 更多