0
from urllib.request import Request, urlopen
req = Request("https://pastebin.pl/view/raw/51c791c6", headers={'User-Agent': 'Mozilla/5.0'})
version = urlopen(req).read() # it's a file like object and works just like a file
print(version)

the output is

b'test'

i'm curious why the b and '' do exist. I tried to remove it by doing this

version=version.replace("b","")

but i got this error :

TypeError: a bytes-like object is required, not 'str'

i wanted to read data from a direct link then use it in the rest of the code, but i'm getting those errors . any help ?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • `.read().decode('utf-8')` – Barmar Aug 06 '21 at 22:15
  • Do you understand what a `bytes-like object` is? What happened when you tried copying and pasting that into a search engine? How about if you search for, say, `python string b prefix`? What happened when you tried reading the documentation for the `urllib` library - what does it tell you about what `.read()` returns? – Karl Knechtel Aug 06 '21 at 22:19
  • @Barmar Not really important but according to the [docs](https://docs.python.org/3/library/stdtypes.html#bytes.decode) the default `encoding` is `"utf-8"` so you don't really need to pass it in as an argument. – TheLizzard Aug 06 '21 at 22:22
  • As a future hint for debugging: make sure to check the *type* of data that you are investigating, not just what it looks like when `print`ed. After all, if your `print` had shown `42`, would you have known whether that was a string or an integer? – Karl Knechtel Aug 06 '21 at 22:25
  • Further to @ KarlKnechtel's comment, if you use `print(repr(version))`, you will get the variable's value and a hit to it's data type. If it prints out `b"abc"`, then it's bytes. If it prints out `"42"`, then it's a string. If it prints out `42`, then it's an int. – TheLizzard Aug 06 '21 at 22:33

0 Answers0