Python: Raw Strings

In Python, a raw string is a special kind of string where backslashes (\) are treated like normal characters, not as escape codes. Usually in Python, \n means a new line, \t means a tab, and so on. But in a raw string, these are not turned into special characters—they stay exactly as you write them.

To make a raw string, just add an r or R in front of the quotes. For example:

normal = "Hello\nWorld"
raw = r"Hello\nWorld"

If you print both:

print(normal)  # Output: Hello
               #         World
print(raw)     # Output: Hello\nWorld

See the difference? The normal string breaks into two lines because of \n, but the raw string keeps the backslash and the letter n just as they are.

Raw strings are super useful when you’re writing regular expressions, file paths, or any string with lots of backslashes.

How to Create Raw Strings

Creating raw strings in Python is easy! You just put an r or R before your string’s opening quote.

Using r"" and r''

You can use either double or single quotes with the r prefix:

text1 = r"Hello\nWorld"
text2 = r'Path\\to\\file'

print(text1)
print(text2)

Both text1 and text2 will keep the backslashes as part of the string, instead of turning them into escape characters.

With Triple Quotes: r'''...''' or r"""..."""

Triple quotes are great when your string is long or spans multiple lines. You can still make it raw by adding the r in front:

long_text = r"""Line 1\nLine 2\\nLine 3"""

print(long_text)

This keeps all the backslashes and characters exactly how you type them.

Multi-line Raw Strings

Raw strings can also go across multiple lines when using triple quotes:

multi_line = r"""
First line\nSecond line\\nThird line
"""

print(multi_line)

Even across lines, the backslashes are not turned into special characters—they stay exactly as they appear.

When and Why to Use Raw Strings

Raw strings are very handy when your text has lots of backslashes. They save you from having to type double backslashes all the time. Let’s look at some common places where raw strings are super useful.

Use in Regular Expressions (re module)

Regular expressions (used for pattern matching) often have backslashes like \d, \w, or \s. If you don’t use raw strings, you’ll need to escape every backslash like \\d, which gets messy.

Using a raw string is much cleaner:

import re

pattern = r"\d+"     # Matches one or more digits
text = "There are 123 apples"

print(re.findall(pattern, text))  # Output: ['123']

Use in File Paths (especially on Windows)

Windows file paths use backslashes (like C:\Users\Edward). Without raw strings, you’d need to write double backslashes like this:

# Without raw string
path = "C:\\Users\\Edward\\Documents"
print(path)

# With raw string
path = r"C:\Users\Edward\Documents"
print(path)

Much easier with a raw string, right?

Use in String Patterns with Many Backslashes

Any time you’re writing a pattern or syntax that uses lots of backslashes (like markup or custom syntax), raw strings make your code cleaner and easier to read.

pattern = r"\start\block{name}"

print(pattern)

This keeps all the slashes exactly how you typed them—no escaping needed.

Working with Escape Sequences in Raw Strings

In normal Python strings, escape sequences are special codes that start with a backslash (\). For example:

  • \n means a new line
  • \t means a tab space
  • \\ means a single backslash

But in a raw string, Python does not treat backslashes as special. It just keeps them exactly as you typed.

How Raw Strings Treat Backslashes

Let’s compare a normal string and a raw string:

normal = "Hello\nWorld"
raw = r"Hello\nWorld"

If you print them:

print(normal)
# Output:
# Hello
# World

print(raw)
# Output:
# Hello\nWorld

In the normal string, \n creates a new line. But in the raw string, it stays as \n.

More Examples

Here’s a tab example:

print("Name:\tEdward")   # Output: Name:    Edward (with tab space)
print(r"Name:\tEdward")  # Output: Name:\tEdward (no tab space)

And here’s one with a backslash:

print("C:\\Users\\Edward")   # Output: C:\Users\Edward
print(r"C:\Users\Edward")    # Output: C:\Users\Edward

In both cases, the raw string keeps the backslashes as they are. That’s what makes raw strings so helpful when dealing with paths or patterns that use lots of slashes.

Printing and Displaying Raw Strings

Raw strings look different when printed depending on how you display them. Let’s look at two ways: just typing the variable name, and using print().

Output of Raw Strings vs Regular Strings

When you type a string directly in the Python shell or use repr(), you’ll see all the backslashes as they are.

regular = "Hello\nWorld"
raw = r"Hello\nWorld"

print(repr(regular))  # Output: 'Hello\nWorld'
print(repr(raw))      # Output: 'Hello\\nWorld'

This shows the -representation- of the string—how Python stores it.

Using print() to Show Raw String Contents Clearly

But when you use print(), Python shows what the string actually looks like when written out:

regular = "Hello\nWorld"
raw = r"Hello\nWorld"

print(regular)  # Output:
# Hello
# World

print(raw)      # Output:
# Hello\nWorld

The raw string keeps the backslash and the n as-is. That’s why raw strings are great when you want to see the exact characters, especially in paths or patterns.

Embedding Quotes in Raw Strings

Sometimes you want to include quotes inside your strings. Raw strings make this a little easier, but you still need to pick the right type of quotes to avoid errors.

Using Single and Double Quotes

If your string contains double quotes, you can wrap it in single quotes—and vice versa:

text1 = r'"Hello", she said.'    # Uses double quotes inside
text2 = r"'Hello', he replied."  # Uses single quotes inside

print(text1)
print(text2)

This works as long as the inside quotes don’t match the outside ones.

Using Triple Quotes

If your string has both single and double quotes, or it’s a multi-line string, triple quotes are your friend:

text = r"""She said, "It's alright."""

print(text)

Triple quotes let you include both ' and " without escaping them. And since it’s a raw string, backslashes stay untouched too.

When to Choose Which Style

  • Use single or double quotes for short strings with only one kind of quote inside.
  • Use triple quotes when your string has both quote types or goes over multiple lines.

This helps keep your raw strings clean and error-free!

Combining Raw Strings with Variables

You can easily combine raw strings with variables using concatenation or string formatting. Let’s look at how.

Concatenation and Formatting

You can concatenate raw strings with regular strings, or combine them with variables:

name = "Edward"
raw_string = r"Hello, "

# Concatenate raw string with regular string
greeting = raw_string + name

print(greeting)  # Output: Hello, Edward

You can also use .format() or f-strings with raw strings:

name = "Edward"

# Using .format()
greeting = r"Hello, {}".format(name)
print(greeting)  # Output: Hello, Edward

# Using f-string
greeting = rf"Hello, {name}"
print(greeting)  # Output: Hello, Edward

With f-strings, don’t forget to add r before the f for raw strings!

Limitation: Raw Strings Can’t End with an Odd Number of Backslashes

A raw string cannot end with a single backslash. For example:

# This will give an error
raw_string = r"Path\to\folder\"

Python will throw a SyntaxError because it expects something after the backslash. To fix this, you can either:

  1. Use double backslashes: r"Path\\to\\folder\\"
  2. Avoid using a backslash at the end in raw strings if it’s unnecessary.

Raw Strings in Practical Scenarios

Raw strings are often used in real-world scenarios like regular expressions, file paths, and custom syntax definitions. Let’s explore some examples.

Regex Example with re.findall()

Regular expressions use a lot of backslashes, and raw strings make them easier to write and understand. Here’s an example that finds all the numbers in a string using re.findall():

import re

text = "The version numbers are 3.9, 11, and 2.7."
pattern = r"\d+(?:\.\d+)?"

# Find all numbers (including decimals)
versions = re.findall(pattern, text)
print(versions)  # Output: ['3.9', '11', '2.7']

Without raw strings, we’d need to escape every backslash, making the pattern harder to read. Raw strings keep everything clean and simple.

File Path Example on Windows

On Windows, file paths often use backslashes. Raw strings make it much easier to handle file paths without worrying about escaping each backslash.

file_path = r"C:\Users\Edward\Documents\Python\script.py"
print(file_path)  # Output: C:\Users\Edward\Documents\Python\script.py

Without raw strings, you’d have to write double backslashes (\\) to avoid errors.

Example Using Raw Strings in Custom Syntax Definitions

If you’re building a custom parser or defining syntax, raw strings help keep patterns clean and readable:

custom_pattern = r"start\block{name}\end"
print(custom_pattern)  # Output: start\block{name}\end

By using raw strings, you don’t need to worry about escaping every backslash in your custom syntax.

Conclusion

To wrap things up, raw strings are a great way to handle strings with lots of backslashes. They help keep your code cleaner and easier to read by preventing you from needing to escape backslashes every time.

  • Use raw strings with r"" or r'' when you want backslashes to remain untouched (especially useful in regular expressions, file paths, or custom syntax).
  • Raw strings can be used with single quotes, double quotes, and even triple quotes for multi-line text.
  • Keep in mind that raw strings can’t end with a single backslash.

By using raw strings, you’ll avoid errors and make your code safer and more readable, especially when dealing with file paths or patterns.