Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages

How to use Python Raw Strings?

Python Raw Strings

Hello everyone! In this article, we’ll be looking at how we can use Python raw strings. This is a powerful feature of Python, using which we can introduce “raw-strings”, without escaping any characters.

A Python raw string is a normal string, prefixed with a r or R.

This treats characters such as backslash (‘\’) as a literal character. This also means that this character will not be treated as a escape character.

Let’s now look at using raw strings, using some illustrative examples!


Python Raw Strings

To understand what a raw string exactly means, let’s consider the below string, having the sequence “\n”.

s = "Hello\tfrom AskPython\nHi"
print(s)

Now, since s is a normal string literal, the sequences “\t” and “\n” will be treated as escape characters.

So, if we print the string, the corresponding escape sequences (tab-space and new-line) will be generated.

Hello    from AskPython
Hi

Now, if we want to make s as a raw string, what will happen?

# s is now a raw string
# Here, both backslashes will NOT be escaped.
s = r"Hello\tfrom AskPython\nHi"
print(s)

Here, both the backslashes will not be treated as escape characters, so Python will not print a tab-space and a new-line.

Rather, it will simply print “\t” and “\n” literally.

Hello\tfrom AskPython\nHi

As you can see, the output is just the same as the input, since no characters are escaped!

Now, let’s look at another scenario where raw strings can be very useful for us, especially when Python strings don’t work.

Consider the below string literal, having the sequence “\x”.

s = "Hello\xfrom AskPython"
print(s)

Here, the sequence “\x” cannot be decoded using the standard unicode encoding.

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 5-7: truncated \xXX escape

This means that we cannot even put it into a string literal. What can we do now?

This is where raw string come handy.

We can easily pass the value into a variable, by considering it as a raw string literal!

s = r"Hello\xfrom AskPython"
print(s)

Now, there is no problem, and we can pass this raw string literal as a normal object!

Hello\xfrom AskPython

NOTE: In some cases, if you’re printing a Python raw string on the console, you may get something like this:

>>> r"Hello\xfrom AskPython"
'Hello\\xfrom AskPython'

Here, the double backslash means that it is a normal Python string with the backslash being escaped. Since the print() function prints regular string literals, the raw string is converted to one such string!


Conclusion

In this article, we learned how we could use Python raw strings to treat special characters without escaping them.


References


Leave a Reply

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