Skip to main content

What Are Python Raw Strings?

Python raw strings are a type of string literal that treats backslashes (\) as literal characters rather than escape characters. This can be particularly useful when dealing with regular expressions, file paths, or any other scenarios where backslashes are commonly used.

To create a raw string, you prefix the string with an r or R. Here’s a quick example:

Regular String

normal_string = "This is a normal string with a newline character:\nNew line." print(normal_string)

Output:

This is a normal string with a newline character: New line.

Raw String

raw_string = r"This is a raw string with a newline character:\nNew line." print(raw_string)

Output:

This is a raw string with a newline character:\nNew line.

Use Case: File Paths

When dealing with Windows file paths, raw strings can help avoid the need to escape backslashes:

Without Raw String

file_path = "C:\\Users\\username\\Documents\\file.txt" print(file_path)

Output:

C:\Users\username\Documents\file.txt

With Raw String

file_path = r"C:\Users\username\Documents\file.txt" print(file_path)

Output:

C:\Users\username\Documents\file.txt

Regular Expressions

Regular expressions often contain backslashes to denote special sequences. Raw strings make these expressions easier to read and write.

Without Raw String

import re pattern = "\\bword\\b" text = "A word in a sentence." matches = re.findall(pattern, text) print(matches)

With Raw String

import re pattern = r"\bword\b" text = "A word in a sentence." matches = re.findall(pattern, text) print(matches)

In both cases, the output will be:

['word']

Key Points

  1. Raw strings start with an r or R.
  2. Backslashes are treated as literal characters.
  3. Useful for regular expressions, file paths, and any situation where backslashes are common.

Time and Space Complexity

Using raw strings does not impact the time or space complexity of your program. It's purely a syntactical convenience to make your code easier to read and write.

Comments