How to Use Raw String in Python: Syntax and Examples
In Python, use a
raw string by prefixing the string literal with r or R, like r"text". This tells Python to treat backslashes \ as literal characters and not as escape characters.Syntax
A raw string is created by adding the letter r or R before the opening quote of a string literal. This means Python will not treat backslashes as special escape characters.
- r"text" or r'text': Raw string with double or single quotes
- Backslashes
\are kept as-is inside the string
python
raw_string = r"C:\Users\Name\Documents" print(raw_string)
Output
C:\Users\Name\Documents
Example
This example shows how a raw string keeps backslashes without needing to double them, which is useful for Windows file paths or regular expressions.
python
normal_string = "C:\\Users\\Name\\Documents" raw_string = r"C:\Users\Name\Documents" print("Normal string:", normal_string) print("Raw string:", raw_string)
Output
Normal string: C:\Users\Name\Documents
Raw string: C:\Users\Name\Documents
Common Pitfalls
One common mistake is to end a raw string with a single backslash, which causes a syntax error because the backslash escapes the quote. Also, raw strings do not process escape sequences, so \n stays as two characters, not a newline.
python
try: bad_raw = r"C:\Users\Name\" except SyntaxError as e: print("SyntaxError:", e) # Correct way to end with backslash correct_raw = r"C:\Users\Name" + "\\" print(correct_raw)
Output
SyntaxError: EOL while scanning string literal
C:\Users\Name\
Quick Reference
- Prefix string with
rorRto make it raw - Backslashes are treated literally, no escape processing
- Cannot end raw string with a single backslash
- Useful for Windows paths and regex patterns
Key Takeaways
Use
r"text" to create raw strings that treat backslashes literally.Raw strings are ideal for Windows file paths and regular expressions.
Avoid ending raw strings with a single backslash to prevent syntax errors.
Raw strings do not interpret escape sequences like
\n as newlines.Prefixing with
r makes your string easier to read and write when backslashes are common.