![]() This is even more important given that Python 3 likes to assume Unicode - so if you are working with files or data sources that use an obscure encoding, make sure to pay extra attention. For example, if we tried using the str() function with UTF-16, we'd be greeted with: If you specify the wrong encoding, the best case is your program crashing because it can't decode the data. Make sure to provide the encoding argument to str() though, otherwise you might get some unexpected results: > str(b) "Let's grab a ?!" Convert Bytes to String with str()įinally, you can use the str() function, which accepts various values and converts them into strings: > b = b'Lets grab a \xf0\x9f\x8d\x95!' > str(b, 'UTF-8') ![]() You don't really need to pass in the encoding parameter, though, it is advised to pass it in: > code(b) Convert Bytes to String with codecsĪlternatively, we can use the built-in codecs module for this purpose as well: > import codecs Passing the encoding format, we've decoded the bytes object into a string and printed it. # Now, let' s decode/ convert them into a string > b = b"Lets grab a \xf0\x9f\x8d\x95!" # Let's check the type > type(b) Let's take a look at how we can convert bytes to a String, using the built-in decode() method for the bytes class: Another bytes-like object added in 2.6 is the bytearray - similar to bytes, but mutable. This was added in Python 2.6, but it served no real purpose other than to prepare for Python 3 as all strings were bytestrings in 2.6.īytestrings in Python 3 are officially called bytes, an immutable sequence of integers in the range 0 <= x < 256. To differentiate these strings from good old bytestrings, we're introduced to a new specifier for them - the b"string". This means that we lost the explicit unicode type: u"string" - every string is a u"string"! Since Python 3, the old ASCII way of doing things had to go, and Python became completely Unicode. Although Python 2 has reached its end of life, many projects still use it, so we'll include both the Python 2 and Python 3 approaches. By the end of this article you will have a clear idea of what these types are and how to effectively handle data using them.ĭepending on the version of Python you're using, this task will differ. In this article, we'll take a look at how to convert Bytes to a String in Python.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |