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

5/5 - (2 votes)

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’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! 🥳

What Is An Octal Escape Sequence?💡

An Octal Escape Sequence is a backslash followed by 1-3 octal digits (0-7) such as \150 which encodes the ASCII character 'h'. Each octal escape sequence encodes one character (except invalid octal sequence \000). You can chain together multiple octal escape sequences to obtain a word.

Problem Formulation

💬 Question: How to convert an octal escape sequence to a string and vice versa in Python?

Examples

OctalString
\101 \102 \103'ABC'
\101 \040 \102 \040 \103'A B C'
\141 \142 \143'abc'
\150 \145 \154 \154 \157'hello'
\150 \145 \154 \154 \157 \040 \167 \157 \162 \154 \144'hello world'

Python Octal to String Built-In Conversion

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.

See here:

>>> 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'

Python Octal to String Explicit Conversion

The bytes.decode('unicode-escape') function converts a given bytes object represented by an (octal) escape sequence to a Python string. For example, br'\101'.decode('unicode-escape') yields the Unicode (string) character 'A'.

def octal_to_string(x):
    ''' Converts an octal escape sequence to a string'''
    return x.decode('unicode-escape')

Example: Convert the octal representations presented above:

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))
    

This leads to the following expected output:

ABC
A B C
abc
hello
hello world

Python String to Octal

To convert a Python string to an octal escape sequence representation, iterate over each character c and convert it to an octal escape sequence using oct(ord(c)).

The result uses octal representation such as '0o123'. You can do string manipulation, such as slicing and string concatenation, to bring it into the final version '\123', for instance.

Here’s the function that converts string to octal escape sequence format:

def string_to_octal(x):
    ''' Converts a string to an octal escape sequence'''
    return '\\' + '\\'.join(oct(ord(c))[2:] for c in x)

Background:

  • The ord() function takes a character (=string of length one) as an input and returns the Unicode number of this character. For example, ord('a') returns the Unicode number 97. The inverse function of ord() is the chr() function, so chr(ord('a')) returns the original character 'a'.
  • The oct() function takes one integer argument and returns an octal string with prefix "0o".

Let’s check how our strings can be converted to the octal escape sequence representation using this function:

strings = ['ABC',
           'A B C',
           'abc',
           'hello',
           'hello world']

for s in strings:
    print(string_to_octal(s))

And here’s the expected output:

\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

If you don’t like the one-liner solution provided above, feel free to use this multi-liner instead that may be easier to read:

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

If you want to train your Python one-liner skills instead, check out my book! 👇

Python One-Liners Book: Master the Single Line First!

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

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.

Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.

You’ll also learn how to:

  • Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  • Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  • Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  • Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
  • Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners on Amazon!!