How to use Python Raw Strings

In this tutorial, we will how to use Python Raw Strings with some simple examples.

Raw Strings are introduced for not to escape any characters in the string. Actually, Python escapes the backslashes (“\”) So we use Prefix before the string. Prefixes are ‘ r ‘  or ‘R’. Here \n is used to return in the new line. “r” and “R” are the Raw Strings which are used not to escape any characters in a String.

Before getting into the examples, I think this post might be helpful for you: Print escape characters in Python and How to escape from \n newline character in Python

Examples of uses of raw strings in Python

Let’s see with Examples,

String = "Hi\nHello world"
print(String)

Output:

Hi

Hello world
String = r"Hi\nHello world"
print(String)

Output:

Hi\nHello world
String = R"Hi\nHello world"
print(String)

Output:

Hi\nHello world

Let’s see, Here “\x” returns the Error because it can’t decode the bytes of string Position.

String = "Hi\xHello world"
print(String)

Output:

File "<string>", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 5-6: truncated \xXX escape

Leave a Reply

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