Skip to content
Home » Raw Strings in Python

Raw Strings in Python

Spread the love

Today we’ll be talking about raw strings.

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.

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

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

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

Here’s the video version of this article:


Spread the love

Leave a Reply