Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Convert an Octal Escape Sequence in Python – And Vice Versa?

#1
How to Convert an Octal Escape Sequence in Python – And Vice Versa?

<div>
<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;}'>
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 142.5px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend" style="font-size: 19.2px;"> 5/5 – (1 vote) </div>
</div>
<p>This tutorial will show you how to convert an </p>
<ul>
<li><strong>octal escape sequence</strong> to a <strong>Python string</strong>, and a</li>
<li><strong>Python string</strong> to an <strong>octal escape sequence</strong>.</li>
</ul>
<p>But let’s quickly recap what an octal escape sequence is in the first place! <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f447.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<div class="wp-block-image">
<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/uplo...00x200.png 300w, https://blog.finxter.com/wp-content/uplo...68x512.png 768w" sizes="(max-width: 894px) 100vw, 894px" /><figcaption class="wp-element-caption"><em>This is you and your friend celebrating after having solved this problem! <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f973.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></em></figcaption></figure>
</div>
<h2>What Is An Octal Escape Sequence?<img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></h2>
<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>
<h2>Problem Formulation</h2>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4ac.png" alt="?" 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>
<h2>Examples</h2>
<figure class="wp-block-table is-style-stripes">
<table>
<thead>
<tr>
<th>Octal</th>
<th>String</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>\101 <code>\</code>102 <code>\</code>103</code></td>
<td><code>'ABC'</code></td>
</tr>
<tr>
<td><code><code>\</code>101 <code>\</code>040 <code>\</code>102 <code>\</code>040 <code>\</code>103</code></td>
<td><code>'A B C'</code></td>
</tr>
<tr>
<td><code>\141 <code>\</code>142 <code>\</code>143</code></td>
<td><code>'abc'</code></td>
</tr>
<tr>
<td><code>\150 <code>\</code>145 <code>\</code>154 <code>\</code>154 <code>\</code>157</code></td>
<td><code>'hello'</code></td>
</tr>
<tr>
<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>
<td><code>'hello world'</code></td>
</tr>
</tbody>
</table>
</figure>
<h2>Python Octal to String Built-In Conversion</h2>
<p class="has-global-color-8-background-color has-background">You don’t need to “convert” an octal escape sequence to a Unicode string if you already have it represented by a bytes object. Python automatically resolves the encoding.</p>
<p>See here:</p>
<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'
b'ABC'
>>> b'101\040\102\040\103'
b'101 B C'
>>> b'\101\040\102\040\103'
b'A B C'
>>> b'\141\142\143'
b'abc'
>>> b'\150\145\154\154\157'
b'hello'
>>> b'\150\145\154\154\157\040\167\157\162\154\144'
b'hello world'</pre>
<h2>Python Octal to String Explicit Conversion</h2>
<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>
<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>
<p><strong>Example</strong>: Convert the octal representations presented above:</p>
<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>
<p>This leads to the following expected output:</p>
<pre class="wp-block-preformatted"><code>ABC
A B C
abc
hello
hello world</code></pre>
</p>
<h2>Python String to Octal</h2>
<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©)</code>. </p>
<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>
<p>Here’s the function that converts string to octal escape sequence format:</p>
<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©)[2:] for c in x)</pre>
<p><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Background</strong>:</p>
<ul>
<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>
<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>
</ul>
<p>Let’s check how our strings can be converted to the octal escape sequence representation using this function:</p>
<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>
<p>And here’s the expected output:</p>
<pre class="wp-block-preformatted"><code>\101\102\103
\101\40\102\40\103
\141\142\143
\150\145\154\154\157
\150\145\154\154\157\40\167\157\162\154\144</code></pre>
<p>If you don’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>
<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©)[2:] return result</pre>
<p>If you want to train your Python one-liner skills instead, check out my book! <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f447.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h2>Python One-Liners Book: Master the Single Line First!</h2>
<p><strong>Python programmers will improve their computer science skills with these useful one-liners.</strong></p>
<div class="wp-block-image">
<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/uplo...00x277.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x708.jpg 768w" sizes="(max-width: 512px) 100vw, 512px" /></a></figure>
</div>
<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 “one-liners”: <strong><em>concise statements of useful functionality packed into a single line of code. </em></strong>You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.</p>
<p>The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms. </p>
<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’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>
<p>You’ll also learn how to:</p>
<ul>
<li>Leverage data structures to <strong>solve real-world problems</strong>, like using Boolean indexing to find cities with above-average pollution</li>
<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>
<li>Calculate basic <strong>statistics </strong>of multidimensional data arrays and the K-Means algorithms for unsupervised learning</li>
<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>
<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>
</ul>
<p>By the end of the book, you’ll know how to <strong><em>write Python at its most refined</em></strong>, and create concise, beautiful pieces of “Python art” in merely a single line.</p>
<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>
</div>


https://www.sickgaming.net/blog/2022/12/...ice-versa/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016