• Skip to primary navigation
  • Skip to main content
Ethan Banks

Ethan Banks

@ecbanks

  • Blog
  • Book
  • Podcasts
  • RSS
  • Show Search
Hide Search

What Does An ‘R’ Before A String Mean In Python?

Ethan Banks · < 1 minute to read
Published February 25, 2022 · Updated February 23, 2022

R Means ‘Raw String’

An ‘r’ before a string tells the Python interpreter to treat backslashes as a literal (raw) character. Normally, Python uses backslashes as escape characters. Prefacing the string definition with ‘r’ is a useful way to define a string where you need the backslash to be an actual backslash and not part of an escape code that means something else in the string.

Examples

1. In this example, Python will interpret each ‘\t’ found in this string as a tab. That is, the backslash+t is interpreted as an escape sequence with a special purpose.

>>> 'path\to\the\thing'
'path\to\the\thing'
>>> print('path\to\the\thing')
path o he hing
>>>

2. By adding the leading r, Python will know that the backslashes are to be interpreted as literal characters and not escape sequences. Interestingly, note how Python represents the literal backslash–as an escape sequence of backslash + backslash.

>>> r'path\to\the\thing'
'path\\to\\the\\thing'
>>> print(r'path\to\the\thing')
path\to\the\thing
>>>

3. This means another way to handle the literal backslash problem is to use backslash + backslash in your string definition. However, this feels like a clunkier way to define the string to me when compared to using ‘r’. Using ‘r’ makes for, I think, more readable code.

>>> 'path\\to\\the\\thing'
'path\\to\\the\\thing'
>>> print('path\\to\\the\\thing')
path\to\the\thing
>>>

For More Information

Python 3 Reference, section 2.4.1, “String and Bytes literals”

Filed Under: Hands OnPublished on ethancbanks.com.

Have You Read…?

  1. What Does An ‘R’ Before A String Mean In Python?
  2. How To Pass API Query Parameters In A Curl Request
  3. Synology Running Out Of Space? Empty The Recycle Bin.
  4. Free Networking Lab Images From Arista, Cisco, nVidia (Cumulus)
  5. How To Create A Python Function You Can Call From Other Scripts
  6. How To Use Grep + Regex To Match Non-200 HTTP Status Codes In Apache Server Logs
  7. When Stretching Layer Two, Separate Your Fate
  8. How To: Simple Juniper SRX Rate-Limiting via Policer
  9. Using AppleScript To Size A Window To 16×9 On MacOS
  10. Auto-Adding Routes When Mac PPTP Connection Comes Up

MORE FREE STUFF!

Check out my IT Education Twitter Collection.
Curated tweets for IT professionals trying to up their game.

twitter mastodon linkedin instagram linkedin

Have a great day. You're doing an outstanding job. 👍

About · Privacy

Copyright © 2007–2023 Ethan Banks