Python raw strings : Explanation with examples

Raw strings in python: Explanation with examples :

raw strings are raw string literals that treat backslash (\) as a literal character. For example, if we try to print a string with a “\n” inside, it will add one line break. But if we mark it as a raw string, it will simply print out the “\n” as a normal character.
raw strings are prefixed with ‘r’ or ‘R’. Let me show you an example of how it looks like :

python raw string

 

So, you can see that the first string dummy_str includes one new-line and the second raw string raw_dummy_str doesn’t include that new-line. Instead, it printed out the string exactly the same as it is including \n.
python raw string

Instead of r, we can also use R :

The output will be the same as above :
python raw string

Using raw string with different string literals :

We know that in python, we have multiple ways to write a string literal. We can use either single quote, double quotes, double-triple quotes or single-triple quotes for a string literal. We can convert any of these string types to raw as well. Let me show you an example :

python raw string

python raw string

Where raw string is used :

Normally raw strings are used where you want the actual raw string that is given, not the processed version of that string. For example, if your string contains any invalid escape character like \x, it will throw one SyntaxError.

One common use case of the raw string is regular expression. Regular expressions are represented as strings and since they contain a lot of backslashes, using them as raw makes more readable.

Invalid raw strings :

Not all raw strings are valid. A raw string that contains only a single backslash is not valid. Similarly, raw strings with an odd number of ending backslash are also not valid.

python raw string

If you try to print any of the string above, it will throw one exception SyntaxError: EOL while scanning string literal.
You can change the program like below, but the output will be different as well :

python raw string

Conclusion :

This python tutorial introduced you to raw string and how they behave. We have also learned how to create different types of raw string, print raw string and invalid raw string with examples. Go through the examples explained above and drop one comment below if you have any queries.

 

You might also like :

Leave a Reply