Categories
Python Answers

How to process escape sequences in a string in Python?

Spread the love

Sometimes, we want to process escape sequences in a string in Python.

In this article, we’ll look at how to process escape sequences in a string in Python.

How to process escape sequences in a string in Python?

To process escape sequences in a string in Python, we can use the Python byte’s decode method.

For instance, we write:

s = "spam\\neggs"
decoded_string = bytes(s, "utf-8").decode("unicode_escape")
print(decoded_string)

We call bytes with string s and 'utf-8' encoding.

Then we call decode with 'unicode_escape' to decode the escape characters.

Therefore, decoded_string is:

spam
eggs

Conclusion

To process escape sequences in a string in Python, we can use the Python byte’s decode method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *