{"id":130310,"date":"2022-12-06T16:47:29","date_gmt":"2022-12-06T16:47:29","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=958372"},"modified":"2022-12-06T16:47:29","modified_gmt":"2022-12-06T16:47:29","slug":"how-to-convert-an-octal-escape-sequence-in-python-and-vice-versa","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2022\/12\/06\/how-to-convert-an-octal-escape-sequence-in-python-and-vice-versa\/","title":{"rendered":"How to Convert an Octal Escape Sequence in Python \u2013 And Vice Versa?"},"content":{"rendered":"\n<div class=\"kk-star-ratings kksr-auto kksr-align-left kksr-valign-top\" data-payload='{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;958372&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;1&quot;,&quot;legendonly&quot;:&quot;&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\\\/5 - (1 vote)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\\\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}'>\n<div class=\"kksr-stars\">\n<div class=\"kksr-stars-inactive\">\n<div class=\"kksr-star\" data-star=\"1\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"2\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"3\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"4\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"5\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<div class=\"kksr-stars-active\" style=\"width: 142.5px;\">\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<\/div>\n<div class=\"kksr-legend\" style=\"font-size: 19.2px;\"> 5\/5 &#8211; (1 vote) <\/div>\n<\/div>\n<p>This tutorial will show you how to convert an <\/p>\n<ul>\n<li><strong>octal escape sequence<\/strong> to a <strong>Python string<\/strong>, and a<\/li>\n<li><strong>Python string<\/strong> to an <strong>octal escape sequence<\/strong>.<\/li>\n<\/ul>\n<p>But let&#8217;s quickly recap what an octal escape sequence is in the first place! <img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f447.png\" alt=\"\ud83d\udc47\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/><\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"894\" height=\"596\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/12\/image-107.png\" alt=\"\" class=\"wp-image-958440\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/12\/image-107.png 894w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/12\/image-107-300x200.png 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/12\/image-107-768x512.png 768w\" sizes=\"auto, (max-width: 894px) 100vw, 894px\" \/><figcaption class=\"wp-element-caption\"><em>This is you and your friend celebrating after having solved this problem! <img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f973.png\" alt=\"\ud83e\udd73\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/><\/em><\/figcaption><\/figure>\n<\/div>\n<h2>What Is An Octal Escape Sequence?<img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f4a1.png\" alt=\"\ud83d\udca1\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/><\/h2>\n<p class=\"has-base-background-color has-background\">An <strong>Octal Escape Sequence<\/strong> is a backslash followed by 1-3 octal digits (<code>0-7<\/code>) such as <code>\\150<\/code> which encodes the ASCII character <code>'h'<\/code>. Each octal escape sequence encodes one character (except invalid octal sequence <code>\\000<\/code>). You can chain together multiple octal escape sequences to obtain a word.<\/p>\n<h2>Problem Formulation<\/h2>\n<p class=\"has-global-color-8-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f4ac.png\" alt=\"\ud83d\udcac\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Question<\/strong>: How to convert an octal escape sequence to a string and vice versa in Python?<\/p>\n<h2>Examples<\/h2>\n<figure class=\"wp-block-table is-style-stripes\">\n<table>\n<thead>\n<tr>\n<th>Octal<\/th>\n<th>String<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td><code>\\101 <code>\\<\/code>102 <code>\\<\/code>103<\/code><\/td>\n<td><code>'ABC'<\/code><\/td>\n<\/tr>\n<tr>\n<td><code><code>\\<\/code>101 <code>\\<\/code>040 <code>\\<\/code>102 <code>\\<\/code>040 <code>\\<\/code>103<\/code><\/td>\n<td><code>'A B C'<\/code><\/td>\n<\/tr>\n<tr>\n<td><code>\\141 <code>\\<\/code>142 <code>\\<\/code>143<\/code><\/td>\n<td><code>'abc'<\/code><\/td>\n<\/tr>\n<tr>\n<td><code>\\150 <code>\\<\/code>145 <code>\\<\/code>154 <code>\\<\/code>154 <code>\\<\/code>157<\/code><\/td>\n<td><code>'hello'<\/code><\/td>\n<\/tr>\n<tr>\n<td><code>\\150 <code>\\<\/code>145 <code>\\<\/code>154 <code>\\<\/code>154 <code>\\<\/code>157 <code>\\<\/code>040 <code>\\<\/code>167 <code>\\<\/code>157 <code>\\<\/code>162 <code>\\<\/code>154 <code>\\<\/code>144<\/code><\/td>\n<td><code>'hello world'<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n<h2>Python Octal to String Built-In Conversion<\/h2>\n<p class=\"has-global-color-8-background-color has-background\">You don&#8217;t need to &#8220;convert&#8221; an octal escape sequence to a Unicode string if you already have it represented by a bytes object. Python automatically resolves the encoding.<\/p>\n<p>See here:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">>>> b'\\101\\102\\103'\nb'ABC'\n>>> b'101\\040\\102\\040\\103'\nb'101 B C'\n>>> b'\\101\\040\\102\\040\\103'\nb'A B C'\n>>> b'\\141\\142\\143'\nb'abc'\n>>> b'\\150\\145\\154\\154\\157'\nb'hello'\n>>> b'\\150\\145\\154\\154\\157\\040\\167\\157\\162\\154\\144'\nb'hello world'<\/pre>\n<h2>Python Octal to String Explicit Conversion<\/h2>\n<p class=\"has-global-color-8-background-color has-background\">The <code>bytes.decode('unicode-escape')<\/code> function converts a given <code>bytes<\/code> object represented by an (octal) escape sequence to a Python string. For example, <code>br'\\101'.decode('unicode-escape')<\/code> yields the Unicode (string) character <code>'A'<\/code>.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"3\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def octal_to_string(x): ''' Converts an octal escape sequence to a string''' return x.decode('unicode-escape')<\/pre>\n<p><strong>Example<\/strong>: Convert the octal representations presented above:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">octals = [br'\\101\\102\\103', br'\\101\\040\\102\\040\\103', br'\\141\\142\\143', br'\\150\\145\\154\\154\\157', br'\\150\\145\\154\\154\\157\\040\\167\\157\\162\\154\\144'] for octal in octals: print(octal_to_string(octal)) <\/pre>\n<p>This leads to the following expected output:<\/p>\n<pre class=\"wp-block-preformatted\"><code>ABC\nA B C\nabc\nhello\nhello world<\/code><\/pre>\n<\/p>\n<h2>Python String to Octal<\/h2>\n<p class=\"has-global-color-8-background-color has-background\">To convert a Python string to an octal escape sequence representation, iterate over each character <code>c<\/code> and convert it to an octal escape sequence using <code>oct(ord(c))<\/code>. <\/p>\n<p>The result uses octal representation such as <code>'0o123'<\/code>. You can do string manipulation, such as <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/introduction-to-slicing-in-python\/\" data-type=\"post\" data-id=\"731\" target=\"_blank\">slicing<\/a> and <a href=\"https:\/\/blog.finxter.com\/daily-python-puzzle-string-concatenation\/\" data-type=\"post\" data-id=\"93\">string concatenation<\/a>, to bring it into the final version <code>'\\123'<\/code>, for instance.<\/p>\n<p>Here&#8217;s the function that converts string to octal escape sequence format:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"3\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def string_to_octal(x): ''' Converts a string to an octal escape sequence''' return '\\\\' + '\\\\'.join(oct(ord(c))[2:] for c in x)<\/pre>\n<p><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/2705.png\" alt=\"\u2705\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Background<\/strong>:<\/p>\n<ul>\n<li>The <code><a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-ord-function\/\" data-type=\"post\" data-id=\"21913\" target=\"_blank\">ord()<\/a><\/code> function takes a character (=string of length one) as an input and returns the Unicode number of this character. For example, <code>ord('a')<\/code> returns the Unicode number <code>97<\/code>. The inverse function of <code>ord()<\/code> is the <code>chr()<\/code> function, so <code>chr(ord('a'))<\/code> returns the original character <code>'a'<\/code>.<\/li>\n<li>The <code><a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-oct-function\/\" data-type=\"post\" data-id=\"24365\" target=\"_blank\">oct()<\/a><\/code> function takes one integer argument and returns an octal string with prefix <code>\"0o\"<\/code>.<\/li>\n<\/ul>\n<p>Let&#8217;s check how our strings can be converted to the octal escape sequence representation using this function:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">strings = ['ABC', 'A B C', 'abc', 'hello', 'hello world'] for s in strings: print(string_to_octal(s))<\/pre>\n<p>And here&#8217;s the expected output:<\/p>\n<pre class=\"wp-block-preformatted\"><code>\\101\\102\\103\n\\101\\40\\102\\40\\103\n\\141\\142\\143\n\\150\\145\\154\\154\\157\n\\150\\145\\154\\154\\157\\40\\167\\157\\162\\154\\144<\/code><\/pre>\n<p>If you don&#8217;t like the <a rel=\"noreferrer noopener\" href=\"https:\/\/pythononeliners.com\/\" data-type=\"URL\" data-id=\"https:\/\/pythononeliners.com\/\" target=\"_blank\">one-liner<\/a> solution provided above, feel free to use this multi-liner instead that may be easier to read:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def string_to_octal(x): ''' Converts a string to an octal escape sequence''' result = '' for c in x: result += '\\\\' + oct(ord(c))[2:] return result<\/pre>\n<p>If you want to train your Python one-liner skills instead, check out my book! <img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f447.png\" alt=\"\ud83d\udc47\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/><\/p>\n<h2>Python One-Liners Book: Master the Single Line First!<\/h2>\n<p><strong>Python programmers will improve their computer science skills with these useful one-liners.<\/strong><\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-medium is-resized\"><a href=\"https:\/\/www.amazon.com\/gp\/product\/B07ZY7XMX8\" target=\"_blank\" rel=\"noopener noreferrer\"><img decoding=\"async\" loading=\"lazy\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-1024x944.jpg\" alt=\"Python One-Liners\" class=\"wp-image-10007\" width=\"512\" height=\"472\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-scaled.jpg 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-300x277.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-768x708.jpg 768w\" sizes=\"auto, (max-width: 512px) 100vw, 512px\" \/><\/a><\/figure>\n<\/div>\n<p><a href=\"https:\/\/amzn.to\/2WAYeJE\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/amzn.to\/2WAYeJE\"><em>Python One-Liners<\/em> <\/a>will teach you how to read and write &#8220;one-liners&#8221;: <strong><em>concise statements of useful functionality packed into a single line of code. <\/em><\/strong>You&#8217;ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.<\/p>\n<p>The book&#8217;s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms. <\/p>\n<p>Detailed explanations of one-liners introduce <strong><em>key computer science concepts <\/em><\/strong>and<strong><em> boost your coding and analytical skills<\/em><\/strong>. You&#8217;ll learn about advanced Python features such as <em><strong>list comprehension<\/strong><\/em>, <strong><em>slicing<\/em><\/strong>, <strong><em>lambda functions<\/em><\/strong>, <strong><em>regular expressions<\/em><\/strong>, <strong><em>map <\/em><\/strong>and <strong><em>reduce <\/em><\/strong>functions, and <strong><em>slice assignments<\/em><\/strong>. <\/p>\n<p>You&#8217;ll also learn how to:<\/p>\n<ul>\n<li>Leverage data structures to <strong>solve real-world problems<\/strong>, like using Boolean indexing to find cities with above-average pollution<\/li>\n<li>Use <strong>NumPy basics<\/strong> such as <em>array<\/em>, <em>shape<\/em>, <em>axis<\/em>, <em>type<\/em>, <em>broadcasting<\/em>, <em>advanced indexing<\/em>, <em>slicing<\/em>, <em>sorting<\/em>, <em>searching<\/em>, <em>aggregating<\/em>, and <em>statistics<\/em><\/li>\n<li>Calculate basic <strong>statistics <\/strong>of multidimensional data arrays and the K-Means algorithms for unsupervised learning<\/li>\n<li>Create more <strong>advanced regular expressions<\/strong> using <em>grouping <\/em>and <em>named groups<\/em>, <em>negative lookaheads<\/em>, <em>escaped characters<\/em>, <em>whitespaces, character sets<\/em> (and <em>negative characters sets<\/em>), and <em>greedy\/nongreedy operators<\/em><\/li>\n<li>Understand a wide range of <strong>computer science topics<\/strong>, including <em>anagrams<\/em>, <em>palindromes<\/em>, <em>supersets<\/em>, <em>permutations<\/em>, <em>factorials<\/em>, <em>prime numbers<\/em>, <em>Fibonacci <\/em>numbers, <em>obfuscation<\/em>, <em>searching<\/em>, and <em>algorithmic sorting<\/em><\/li>\n<\/ul>\n<p>By the end of the book, you&#8217;ll know how to <strong><em>write Python at its most refined<\/em><\/strong>, and create concise, beautiful pieces of &#8220;Python art&#8221; in merely a single line.<\/p>\n<p><strong><a href=\"https:\/\/amzn.to\/2WAYeJE\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/amzn.to\/2WAYeJE\"><em>Get your Python One-Liners on Amazon!!<\/em><\/a><\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>5\/5 &#8211; (1 vote) This tutorial will show you how to convert an octal escape sequence to a Python string, and a Python string to an octal escape sequence. But let&#8217;s quickly recap what an octal escape sequence is in the first place! This is you and your friend celebrating after having solved this problem! [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-130310","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/130310","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=130310"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/130310\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=130310"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=130310"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=130310"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}