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 call decode to decode the string.
For instance, we write
my_string = "spam\\neggs"
decoded_string = bytes(my_string, "utf-8").decode("unicode_escape")
print(decoded_string)
to call bytes with my_string and the 'utf-8' encoding to convert the string to bytes.
And then we call decode with 'unicode_escape' to return the decoded string without the escape characters.
Conclusion
To process escape sequences in a string in Python, we call decode to decode the string.