Tutorial

How To Use Python Raw String

Updated on December 20, 2022
authorauthor

Pankaj and Andrea Anderson

How To Use Python Raw String

Introduction

You can create a raw string in Python by prefixing a string literal with r or R. Python raw string treats the backslash character (\) as a literal character. Raw string is useful when a string needs to contain a backslash, such as for a regular expression or Windows directory path, and you don’t want it to be treated as an escape character. This article covers the basics of how Python raw strings work and provides a few common examples of how to use raw strings to include special characters in strings.

The examples in this article use the Python interactive console in the command line to demonstrate different raw string scenarios.

Including a Newline Character in a String Using Raw String

This example uses a string with a value: Hi\nHello. If you try to assign this value to a normal string, then the newline character (\n) creates a new line:

  1. s = 'Hi\nHello'

Print the string:

  1. print(s)

The output is:

Hi
Hello

The output shows that the newline character results in a new line.

To include the newline character in the string, prefix the string variable with r or R to create a raw string:

  1. raw_s = r'Hi\nHello'

Print the string:

  1. print(raw_s)

The output is:

Hi\nHello

The output includes the newline character.

Including Double Backslash Characters in a String Using Raw String

If you try to include double backslash characters, such as for a hostname path, in a normal string, then the first backslash character won’t print because the compiler considers the backslash to be an escape indicator.

For example, create a string that contains a path:

  1. s = '\\examplehost\digitalocean\content\'

Print the string:

  1. print(s)

The output is:

\examplehost\digitalocean\content\

The output shows that the first backslash character isn’t included in the string.

To include both backslash characters in the string, prefix the string variable with r or R to create a raw string:

  1. s = r'\\examplehost\digitalocean\content\'

Print the string:

  1. print(s)

The output is:

\\examplehost\digitalocean\content\

The output includes both backslash characters.

Troubleshooting Quotes and Backslash Characters in Raw Strings

In a raw string, quotes can still be escaped with a single backslash character, however, the backslash character remains in the resulting raw string.

In addition, a raw string can’t end with an odd number of backslash characters. Because of this feature, you can’t create a raw string that contains a single backslash character, so r"/" is an invalid string.

Invalid Raw String Examples

In this example, the end quote is missing from the output since it’s being escaped by the backslash character resulting in an unterminated string literal error:

r'\'

In this example, the first two backslashes will escape each other, and the third one will try to escape the end quote, resulting in an unterminated string literal error:

r'ab\\\'

Valid Raw String Examples

Here are some examples of valid raw strings that include quotes and backslash characters.

Create a raw string that escapes quotes:

  1. s = r"\"\""

Print the string:

  1. print(s)

The output is:

\"\"

The output shows that the backslash characters escape the quotes so that the string doesn’t terminate, but the backslash characters remain in the result string.

Create a raw string with an even number of backslash characters:

  1. s = R'ab\\'

Print the string:

  1. print(s)

The output is:

ab\\

The output shows that the even number of backslash characters are included in the result string.

Conclusion

In this article, you learned the basics of raw strings in Python. Continue your learning about Python strings.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author


Default avatar

Technical Editor


Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
October 14, 2019

Hi expert, I have a problem about Python Raw String. I had a list data, it included a string which likes “\183456\data\image” I want to use this string(a directory) to access a file, but it comes up an error. “\1” can’t not be regarded as a string, I can’t use the “r” because the list data are dynamically generated. I would really appreciate if you could answer my question.

- Willy

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    July 4, 2019

    Thanks mate! Quite short and simple, but very handy!

    - Pedro de Oliveira

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      March 15, 2019

      1. raw_s = r’\‘’ print(raw_s) 2.raw_s = r’ab\\’ print(raw_s) how (2) can be correct in raw string,because as far as i understood rawstring places a backslash whenever it sees a backslash or when it is not escaping a quote. If that is the case then then it should matter how many consecutive backslashes are present in a string, but it is not dealing in that way ,why? please make my concept clear.

      - amar

        Try DigitalOcean for free

        Click below to sign up and get $200 of credit to try our products over 60 days!

        Sign up

        Join the Tech Talk
        Success! Thank you! Please check your email for further details.

        Please complete your information!

        Become a contributor for community

        Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

        DigitalOcean Documentation

        Full documentation for every DigitalOcean product.

        Resources for startups and SMBs

        The Wave has everything you need to know about building a business, from raising funding to marketing your product.

        Get our newsletter

        Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

        New accounts only. By submitting your email you agree to our Privacy Policy

        The developer cloud

        Scale up as you grow — whether you're running one virtual machine or ten thousand.

        Get started for free

        Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

        *This promotional offer applies to new accounts only.