Raw string python – Python Raw Strings With Examples

Raw string python: A raw string in Python is formed by prefixing a string literal with ‘r’ or ‘R’. A backslash (\) is treated as a literal character in Python raw string. This is useful when we want to have a string with a backslash in it but don’t want it to be interpreted as an escape character.

This feature allows us to pass string literals that cannot be decoded normally, such as the sequence “\x.”

For example – r”Good morning\tBtechgeeks”

Raw Strings in Python:

# Give the string as static input and store it in a variable.
gvn_str = "Hello this\t is\nbtechgeeks"
# Print the given string
print(gvn_str)

Output:

Hello this	 is
btechgeeks

Because gvn_str is a regular string literal, the sequences “\t” and “\n” will be considered as escape characters.

As a result, when we print the string, the corresponding escape sequences (tab-space and new-line) are generated.

# Give the raw string as static input and store it in a variable.
# Both backslashes(\t,\n) will NOT be escaped in this case.
gvn_rawstr = r"Hello this\t is\nbtechgeeks"
# Print the given string
print(gvn_rawstr)

Output:

Hello this\t is\nbtechgeeks

Python raw string: Because both backslashes are not considered as escape characters in this case, Python will NOT display a tab-space and a new line.

It will just print “t” and “n” literally.
As you can see, the output is identical to the input because no characters are escaped.

Let’s have a look at another situation where raw strings can use, especially when Python strings don’t function.

See the string literal with the sequence “x” below:

# Give the string as static input and store it in a variable.
gvn_str =  "Good morning\xBtechgeeks"
# Print the given string
print(gvn_str)

Output:

 File "/home/jdoodle.py", line 2
gvn_str = "Good morning\xBtechgeeks"
^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 12-14: 
truncated \xXX escape

Explanation:

The sequence "x" cannot be decoded using normal Unicode encoding in this case.

This means we can’t even use it as a string literal. What are our options now?

Here’s where the raw string comes in helpful.

By treating the value as a raw string literal, we can easily pass it into a variable.

# Give the string as static input and store it in a variable.
gvn_str =  r"Good morning\xBtechgeeks"
# Print the given string
print(gvn_str)

Output:

Good morning\xBtechgeeks

There is no longer any issue, and we may give this raw string literal as a normal object.

Note: If you print a Python raw string to the terminal, you may receive anything like below in some cases.

Example:

>>> gvn_str =  r"Good morning\xBtechgeeks"

Output:

 'Good morning\\xBtechgeeks'

The double backslash indicates that this is a regular Python string with the backslash escaped. Because the print() method outputs normal string literals, the raw string gets converted to one such string.