Search code examples
python-3.xurllib3

Python - part of str [urllib3 data]


I'm Trying to delete 2 chars from start of the str and 1 char from the end

import urllib3
target_url="www.klimi.hys.cz/nalada.txt"

http = urllib3.PoolManager()
r = http.request('GET', target_url)
print(r.status)
print(r.data)
print()

And Output is

200
b'smutne'

I need to output be only "smutne", only this, not the " b' " and " ' "


Solution

  • When you have bytes, you'll need them to decode it into a string with the appropriate encoding type. For example, if you have a ASCII characters as bytes, you can do:

    >>> foo = b'mystring'
    >>> print(foo)
    b'mystring'
    >>> print(foo.decode('ascii'))
    'mystring'
    

    Or, more commonly, you probably have Unicode characters (which includes most of the ASCII character codes too):

    >>> print(foo.decode('utf-8'))
    'mystring'
    

    This will work if you have glyphs with accents and such.

    More on Python encoding/decoding here: https://docs.python.org/3/howto/unicode.html

    In the particular case of urllib3, r.data returns bytes that you'll need to decode in order to use as a string if that's what you want.