{"id":1081,"date":"2023-04-28T22:35:00","date_gmt":"2023-04-28T17:05:00","guid":{"rendered":"https:\/\/geekpython.in\/?p=1081"},"modified":"2023-08-15T13:25:36","modified_gmt":"2023-08-15T07:55:36","slug":"convert-bytes-into-string","status":"publish","type":"post","link":"https:\/\/geekpython.in\/convert-bytes-into-string","title":{"rendered":"How To Convert Bytes To A String &#8211; Different Methods Explained"},"content":{"rendered":"\n<p>In Python, a byte string is a sequence of bytes, which are the fundamental building blocks of digital data such as images, audio, and videos. Byte strings differ from regular strings in that they are made up of bytes rather than characters.<\/p>\n\n\n\n<p>Sometimes we work on projects where we need to handle bytes, and we needed to convert them into Python strings in order to perform specific operations.<\/p>\n\n\n\n<p>In this article, we&#8217;ll see the ways how we can convert the bytes string into the normal string in Python.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"heading-bytes-string\"><a href=\"https:\/\/geekpython.in\/convert-bytes-into-string#heading-bytes-string\"><\/a>Bytes string<\/h2>\n\n\n\n<p>In Python, a byte string can be generated by prefixing the character &#8220;<code>b<\/code>&#8221; before the string&#8217;s quotation mark. The following example will demonstrate how to generate a byte string.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">byte_str = b\"GeekPython\"<\/pre><\/div>\n\n\n\n<p>We created a byte string containing the characters &#8220;<code>G<\/code>&#8220;, &#8220;<code>e<\/code>&#8220;, &#8220;<code>e<\/code>&#8220;, &#8220;<code>k<\/code>&#8220;, &#8220;<code>P<\/code>&#8220;, &#8220;<code>y<\/code>&#8220;, &#8220;<code>t<\/code>&#8220;, &#8220;<code>h<\/code>&#8220;, &#8220;<code>o<\/code>&#8221; and &#8220;<code>n<\/code>&#8220;.<\/p>\n\n\n\n<p>The upper byte string was straightforward and easy to generate, but the byte string of any image would be different from what we saw in the upper part.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1294\" height=\"601\" src=\"https:\/\/geekpython.in\/wp-content\/uploads\/2023\/08\/ima_bytes.png\" alt=\"Image's byte string\" class=\"wp-image-1094\" srcset=\"https:\/\/geekpython.in\/wp-content\/uploads\/2023\/08\/ima_bytes.png 1294w, https:\/\/geekpython.in\/wp-content\/uploads\/2023\/08\/ima_bytes-300x139.png 300w, https:\/\/geekpython.in\/wp-content\/uploads\/2023\/08\/ima_bytes-1024x476.png 1024w, https:\/\/geekpython.in\/wp-content\/uploads\/2023\/08\/ima_bytes-768x357.png 768w\" sizes=\"auto, (max-width: 1294px) 100vw, 1294px\" \/><\/figure>\n\n\n\n<p>These bytes combine to make an image. These byte strings vary based on the type of data. We&#8217;ll see the methods to convert the byte string into a normal string.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"heading-method-1-decode-method\"><a href=\"https:\/\/geekpython.in\/convert-bytes-into-string#heading-method-1-decode-method\"><\/a>Method 1 &#8211; decode method<\/h2>\n\n\n\n<p>The&nbsp;<code>decode<\/code>&nbsp;method is the most commonly used method by developers. The&nbsp;<code>decode<\/code>&nbsp;method converts a byte string into a normal string using the specified&nbsp;<code>encoding<\/code>. Let us illustrate with an example.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \"># Byte string\nbyte_str = b\"GeekPython\"\n\n# Converting\nnor_str = byte_str.decode(encoding='utf-8')\nprint(nor_str)\n# Checking the type of string\nprint(f'Type: {type(nor_str)}')\n\n----------\nGeekPython\nType: &lt;class 'str'&gt;<\/pre><\/div>\n\n\n\n<p>We used the&nbsp;<code>decode<\/code>&nbsp;method on the variable&nbsp;<code>byte_str<\/code>, which contains a byte string, and set the encoding to&nbsp;<code>utf-8<\/code>. The output shows that our byte string was converted into a normal string.<\/p>\n\n\n\n<p>Here&#8217;s an example of converting the image&#8217;s byte to a string. We first saved the image&#8217;s bytes in a file before converting them to a normal string.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">with open('binary_file', 'rb') as file:\n    chars = file.read()\n    print(f'Content type in file before: {type(chars)}')\n    # print(chars)\n    decoded = chars.decode('utf-8', errors='ignore')\n    # print(decoded)\n    print(f'Content type in file after: {type(decoded)}')\n\n----------\nContent type in file before: &lt;class 'bytes'&gt;\nContent type in file after: &lt;class 'str'&gt;<\/pre><\/div>\n\n\n\n<p>Note:&nbsp;<code>utf-8<\/code>&nbsp;encoding is unlikely to be used to decode the image&#8217;s byte, and if it is, the decoding will produce&nbsp;<a target=\"_blank\" href=\"https:\/\/en.wikipedia.org\/wiki\/Mojibake\" rel=\"noreferrer noopener\">mojibake<\/a>(garbled text).<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"heading-method-2-codecs-module\"><a href=\"https:\/\/geekpython.in\/convert-bytes-into-string#heading-method-2-codecs-module\"><\/a>Method 2 &#8211; codecs module<\/h2>\n\n\n\n<p>It&#8217;s the same method as before, but this time we&#8217;ll use the&nbsp;<code>decode<\/code>&nbsp;method from Python&#8217;s&nbsp;<code>codecs<\/code>&nbsp;module.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">import codecs\n\nbstr = b'\\xa3'\nemoji = b'\\xF0\\x9F\\x98\\x86\\xF0\\x9F\\x98\\x81\\xF0\\x9F\\x98\\x82'\n\nchar_dec = codecs.decode(bstr, encoding='cp1252')\nprint(char_dec)\nprint(f'Type(Before decoding): {type(bstr)}')\nprint(f'Type(After decoding): {type(char_dec)}')\n\nprint('-'*20)\n\ndec = codecs.decode(emoji, encoding='utf-8')\nprint(dec)\nprint(f'Type(Before decoding): {type(emoji)}')\nprint(f'Type(After decoding): {type(dec)}')<\/pre><\/div>\n\n\n\n<p>In the first block of code, we decoded the bytes stored in the variable&nbsp;<code>bstr<\/code>&nbsp;and specified the&nbsp;<code>cp1252<\/code>&nbsp;encoding (used for decoding single-byte Latin alphabet characters).<\/p>\n\n\n\n<p>In the second block of code, we decoded the emoji bytes using the default encoding.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">\u00a3\nType(Before decoding): &lt;class 'bytes'&gt;\nType(After decoding): &lt;class 'str'&gt;\n--------------------\n\ud83d\ude06\ud83d\ude01\ud83d\ude02\nType(Before decoding): &lt;class 'bytes'&gt;\nType(After decoding): &lt;class 'str'&gt;<\/pre><\/div>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"heading-method-3-str-method\"><a href=\"https:\/\/geekpython.in\/convert-bytes-into-string#heading-method-3-str-method\"><\/a>Method 3 &#8211; str method<\/h2>\n\n\n\n<p>In this approach, we&#8217;ll use the most basic technique, which is the&nbsp;<code>str<\/code>&nbsp;method. The&nbsp;<code>str<\/code>&nbsp;method converts data to a string, which we&#8217;ll use to convert the byte string to a regular string.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">byte_str = b'GeekPython'\nprint(type(byte_str))\n\nprint('-'*20)\n\n# Using str method with encoding\nnormal_str = str(byte_str, 'utf-8')\nprint(normal_str)\nprint(type(normal_str))\n\nprint('-'*20)\n\n# Using str method without encoding\nwithout_encoding = str(byte_str)\nprint(without_encoding)\nprint(type(without_encoding))<\/pre><\/div>\n\n\n\n<p>In the first block of code, we used the&nbsp;<code>str<\/code>&nbsp;method and passed a byte string with the&nbsp;<code>utf-8<\/code>&nbsp;encoding. In the second block of code, we did the same thing as in the first, but we didn&#8217;t specify the encoding.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">&lt;class 'bytes'&gt;\n--------------------\nGeekPython\n&lt;class 'str'&gt;\n--------------------\nb'GeekPython'\n&lt;class 'str'&gt;<\/pre><\/div>\n\n\n\n<p>We can see a difference in both outputs, but they are both in string format.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"heading-comparing-execution-time\"><a href=\"https:\/\/geekpython.in\/convert-bytes-into-string#heading-comparing-execution-time\"><\/a>Comparing execution time<\/h2>\n\n\n\n<p>We can compare the execution time of these three methods to see which one is the fastest.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">import timeit\n\nprint(\"Execution time of decode method:\")\nprint(timeit.timeit(stmt='byte_str=b\"GeekPython\";n=byte_str.decode(\"utf-8\")'))\n\nprint('-'*20)\n\nprint(\"Execution time of codecs.decode method:\")\nprint(timeit.timeit(setup=\"import codecs\", stmt='byte_str=b\"GeekPython\";n=codecs.decode(byte_str, \"utf-8\")'))\n\nprint('-'*20)\n\nprint(\"Execution time of str method:\")\nprint(timeit.timeit(stmt='byte_str=b\"GeekPython\";n=str(byte_str, \"utf-8\")'))<\/pre><\/div>\n\n\n\n<p>We measured the execution time of the code snippets using the&nbsp;<a rel=\"noreferrer noopener\" href=\"https:\/\/docs.python.org\/3\/library\/timeit.html#module-timeit\" target=\"_blank\"><code>timeit<\/code><\/a>&nbsp;module.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">Execution time of decode method:\n0.14236710011027753\n--------------------\nExecution time of codecs.decode method:\n0.7000259000342339\n--------------------\nExecution time of str method:\n0.177455399883911<\/pre><\/div>\n\n\n\n<p>The&nbsp;<code>decode<\/code>&nbsp;method code snippet took less time to execute than the other two methods. The execution time difference between the&nbsp;<code>decode<\/code>&nbsp;method and the&nbsp;<code>str<\/code>&nbsp;method is not that big.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"heading-conclusion\"><a href=\"https:\/\/geekpython.in\/convert-bytes-into-string#heading-conclusion\"><\/a>Conclusion<\/h2>\n\n\n\n<p>In this article, we&#8217;ve learned the different methods to convert the byte string into a regular string. We&#8217;ve seen three methods which are as follows:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>using the<\/strong>&nbsp;<code><strong>decode<\/strong><\/code>&nbsp;<strong>method<\/strong><\/li>\n\n\n\n<li><strong>using the<\/strong>&nbsp;<code><strong>codecs.decode<\/strong><\/code>&nbsp;<strong>method<\/strong><\/li>\n\n\n\n<li><strong>using the<\/strong>&nbsp;<code><strong>str<\/strong><\/code>&nbsp;<strong>method<\/strong><\/li>\n<\/ul>\n\n\n\n<p>These three methods can be used to convert a byte string to a regular string, but the first choice for the developers can be the&nbsp;<code>decode<\/code>&nbsp;method because it is simpler and consumes less time than the other two methods.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p>\ud83c\udfc6<strong>Other articles you might be interested in if you liked this one<\/strong><\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/4-ways-of-string-formatting-in-python-guide\" rel=\"noreferrer noopener\">Here&#8217;s how we can format the string in different ways<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/python-enumerate-function-with-example-beginners-guide\" rel=\"noreferrer noopener\">Number the iterable objects using the enumerate() function in Python<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/ways-to-remove-whitespaces-from-the-string-in-python-with-examples-beginners-guide\" rel=\"noreferrer noopener\">Different ways to remove whitespaces from the string<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/python-bitwise-operators-with-examples-explained-in-detail\" rel=\"noreferrer noopener\">How do bitwise operators work behind the scenes in Python<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/understanding-args-and-kwargs-in-python-best-practices-and-guide\" rel=\"noreferrer noopener\">What are args and kwargs parameters within the function in Python<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/asyncio-how-to-use-asyncawait-in-python\" rel=\"noreferrer noopener\">Asynchronous programming in Python using asyncio module<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/python-virtual-environments-venv\" rel=\"noreferrer noopener\">Create a virtual environment to create an isolated space for projects in Python<\/a>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><strong>That&#8217;s all for now<\/strong><\/p>\n\n\n\n<p><strong>Keep Coding\u270c\u270c<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In Python, a byte string is a sequence of bytes, which are the fundamental building blocks of digital data such as images, audio, and videos. Byte strings differ from regular strings in that they are made up of bytes rather than characters. Sometimes we work on projects where we need to handle bytes, and we [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":1083,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"ocean_post_layout":"","ocean_both_sidebars_style":"","ocean_both_sidebars_content_width":0,"ocean_both_sidebars_sidebars_width":0,"ocean_sidebar":"0","ocean_second_sidebar":"0","ocean_disable_margins":"enable","ocean_add_body_class":"","ocean_shortcode_before_top_bar":"","ocean_shortcode_after_top_bar":"","ocean_shortcode_before_header":"","ocean_shortcode_after_header":"","ocean_has_shortcode":"","ocean_shortcode_after_title":"","ocean_shortcode_before_footer_widgets":"","ocean_shortcode_after_footer_widgets":"","ocean_shortcode_before_footer_bottom":"","ocean_shortcode_after_footer_bottom":"","ocean_display_top_bar":"default","ocean_display_header":"default","ocean_header_style":"","ocean_center_header_left_menu":"0","ocean_custom_header_template":"0","ocean_custom_logo":0,"ocean_custom_retina_logo":0,"ocean_custom_logo_max_width":0,"ocean_custom_logo_tablet_max_width":0,"ocean_custom_logo_mobile_max_width":0,"ocean_custom_logo_max_height":0,"ocean_custom_logo_tablet_max_height":0,"ocean_custom_logo_mobile_max_height":0,"ocean_header_custom_menu":"0","ocean_menu_typo_font_family":"0","ocean_menu_typo_font_subset":"","ocean_menu_typo_font_size":0,"ocean_menu_typo_font_size_tablet":0,"ocean_menu_typo_font_size_mobile":0,"ocean_menu_typo_font_size_unit":"px","ocean_menu_typo_font_weight":"","ocean_menu_typo_font_weight_tablet":"","ocean_menu_typo_font_weight_mobile":"","ocean_menu_typo_transform":"","ocean_menu_typo_transform_tablet":"","ocean_menu_typo_transform_mobile":"","ocean_menu_typo_line_height":0,"ocean_menu_typo_line_height_tablet":0,"ocean_menu_typo_line_height_mobile":0,"ocean_menu_typo_line_height_unit":"","ocean_menu_typo_spacing":0,"ocean_menu_typo_spacing_tablet":0,"ocean_menu_typo_spacing_mobile":0,"ocean_menu_typo_spacing_unit":"","ocean_menu_link_color":"","ocean_menu_link_color_hover":"","ocean_menu_link_color_active":"","ocean_menu_link_background":"","ocean_menu_link_hover_background":"","ocean_menu_link_active_background":"","ocean_menu_social_links_bg":"","ocean_menu_social_hover_links_bg":"","ocean_menu_social_links_color":"","ocean_menu_social_hover_links_color":"","ocean_disable_title":"default","ocean_disable_heading":"default","ocean_post_title":"","ocean_post_subheading":"","ocean_post_title_style":"","ocean_post_title_background_color":"","ocean_post_title_background":0,"ocean_post_title_bg_image_position":"","ocean_post_title_bg_image_attachment":"","ocean_post_title_bg_image_repeat":"","ocean_post_title_bg_image_size":"","ocean_post_title_height":0,"ocean_post_title_bg_overlay":0.5,"ocean_post_title_bg_overlay_color":"","ocean_disable_breadcrumbs":"default","ocean_breadcrumbs_color":"","ocean_breadcrumbs_separator_color":"","ocean_breadcrumbs_links_color":"","ocean_breadcrumbs_links_hover_color":"","ocean_display_footer_widgets":"default","ocean_display_footer_bottom":"default","ocean_custom_footer_template":"0","ocean_post_oembed":"","ocean_post_self_hosted_media":"","ocean_post_video_embed":"","ocean_link_format":"","ocean_link_format_target":"self","ocean_quote_format":"","ocean_quote_format_link":"post","ocean_gallery_link_images":"off","ocean_gallery_id":[],"footnotes":""},"categories":[2],"tags":[12,31],"class_list":["post-1081","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-python","tag-python3","entry","has-media"],"_links":{"self":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1081","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/comments?post=1081"}],"version-history":[{"count":5,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1081\/revisions"}],"predecessor-version":[{"id":1293,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1081\/revisions\/1293"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/media\/1083"}],"wp:attachment":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/media?parent=1081"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/categories?post=1081"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/tags?post=1081"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}