2

I am using python 3, and don't understand why the output has b in each start of the line. I don't think this is the case for python 2. Why is this and how to remove it? Thanks

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())

output looks like this

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'
Ogre Magi
  • 1,445
  • 3
  • 13
  • 14

1 Answers1

4

I know this question has been answered over a year ago, I found a simple. I simply added a decode() to my line of code.

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)

This worked an removed the b from the beginning of each line.