Today we’ll be talking about raw strings.
A raw string is a string with suppressed escape sequences.
If you want to learn more about escape sequences, you can read my article about them.
Sometimes we want to print an escape sequence literally, let’s say the escape character \n. There are two ways we can do it. But before that have a look at what happens if we just use it like we’ve been doing so far:
>>> print("We use the \n character for newline.")
We use the
character for newline.
And now what we want is to print the escape sequence literally, so that it doesn’t act like an escape sequence.
The first method is to double the slash character:
>>> print("We use the \\n character for newline.")
We use the \n character for newline.
The other method consists in preceding the opening quote with a small or capital letter R:
>>> print(r"We use the \n character for newline.")
We use the \n character for newline.
>>> print(R"We use the \n character for newline.")
We use the \n character for newline.
This is especially useful if there are many escape sequences in the string. Let’s try to print a path. It doesn’t work because the slashes in the path must be preceded by escape characters:
>>> print("C:\Users\user-1\Desktop\projects")
File "<stdin>", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
So, let’s add the escape characters. All we have to do is add one more slash before each existing slash. Now it works:
>>> print("C:\\Users\\user-1\\Desktop\\projects")
C:\Users\user-1\Desktop\projects
But it’s quite a lot of tedious work, especially if there are many of them. That’s where raw strings come in handy:
>>> print(r"C:\Users\user-1\Desktop\projects")
C:\Users\user-1\Desktop\projects
Here’s the video version of this article: