Python Raw Strings (r”…”): How to Disable Backslash Escapes

When handling strings in Python, the backslash (\) has a special meaning as an “escape sequence.” For example, \n is interpreted as a newline, and \t as a tab. While this feature is useful, it becomes inconvenient when you want to treat the backslash itself as a character, such as in Windows file paths (C:\Users\Name) or regular expression patterns (\d+).

Normally, you need to write double backslashes \\ to represent a single backslash.

# Normal string: Need to write double backslashes \\
win_path = "C:\\Users\\Profile\\Documents"
print(win_path)

Output:

C:\Users\Profile\Documents

This is hard to read and prone to errors. The solution to this problem is Raw Strings.


目次

What is a Raw String (r"...")?

You can create a Raw String by adding r or R immediately before the starting quote (" or ') of a string literal. Inside a Raw String, the backslash (\) loses its special meaning as an escape character and is treated as a simple character (a literal backslash).


Usage Examples of Raw Strings

1. Windows File Paths

The most common use for Raw Strings is writing Windows file paths. You don’t need to write \\, so you can write the path exactly as it looks.

# Using Raw String (r"...")
# Backslashes are treated as characters
win_path_raw = r"C:\Users\Profile\Documents\note.txt"
print(win_path_raw)

# \n and \t are NOT interpreted as special characters
test_string = r"Line 1\nLine 2\tTabbed"
print(test_string)

Output:

C:\Users\Profile\Documents\note.txt
Line 1\nLine 2\tTabbed

You can see that \n is not converted to a newline but is output as the two characters \ and n.

2. Regular Expression Patterns

Another situation where Raw Strings are very useful is regular expressions. Regular expressions frequently use special sequences involving backslashes, like \d (digit) or \w (word character). Without Raw Strings, you would need to escape the backslash for Python (\\d), making the pattern very complex.

import re

# Regular expression pattern string
# Want to match a zip code (e.g., 123-4567)
zip_code = "My zip is 330-0061."

# 1. Normal string (Not recommended): Need to write '\\d'
pattern_normal = "\\d{3}-\\d{4}" 

# 2. Raw String (Recommended): Write exactly as seen using r'...'
pattern_raw = r"\d{3}-\d{4}"

match1 = re.search(pattern_normal, zip_code)
match2 = re.search(pattern_raw, zip_code)

print(f"Match with normal string: {match1.group(0)}")
print(f"Match with Raw String: {match2.group(0)}")

Output:

Match with normal string: 330-0061
Match with Raw String: 330-0061

pattern_raw is much more intuitive and readable as a regular expression pattern.


Limitations of Raw Strings (Note)

There is one syntactic limitation to Raw Strings: You cannot end a Raw String with an odd number of backslashes.

# This is OK (Ends with even number of backslashes)
# ok_path = r"C:\Temp\\"

# This causes a SyntaxError
# error_path = r"C:\Temp\"

This is because the Python interpreter tries to escape the closing quote (") with the final \, causing it to think the string is not closed. If you need a \ at the end of the string (e.g., to indicate a directory), you should concatenate a Raw String and a normal string like this:

# Directory path (Need \ at the end)
dir_path = r"C:\Temp" + "\\"
print(dir_path)

Output:

C:\Temp\

Summary

  • Create a Raw String by adding the r prefix, like r"..." or r'...'.
  • Inside a Raw String, backslashes (\) lose their escape function and are treated as normal characters.
  • They are extremely useful for writing Windows file paths and regular expression patterns, improving readability.
  • Note that you cannot end a Raw String with a single backslash \.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次