Hướng dẫn python print raw string

Python raw string is created by prefixing a string literal with ‘r’ or ‘R’. Python raw string treats backslash (\) as a literal character. This is useful when we want to have a string that contains backslash and don’t want it to be treated as an escape character.

Nội dung chính

  • Python Raw String
  • Python Raw String and Quotes
  • Want to learn more? Join the DigitalOcean Community!
  • Introduction to the Python raw strings
  • Use raw strings to handle file path on Windows
  • Convert a regular string into a raw string
  • How do you print raw strings in Python?
  • What is a raw string in Python?
  • How do you convert a string to a raw string in Python?
  • How can we make a string tab a raw string?

Python Raw String

Let’s say we want to create a string Hi\nHello in python. If we try to assign it to a normal string, the \n will be treated as a new line.

s = 'Hi\nHello'
print(s)

Output:

Hi
Hello

Let’s see how raw string helps us in treating backslash as a normal character.

raw_s = r'Hi\nHello'
print(raw_s)

Output: Hi\nHello Let’s see another example where the character followed by backslash doesn’t have any special meaning.

>>> s = 'Hi\xHello'
  File "<input>", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \xXX escape

We got the error because python doesn’t know how to decode ‘\x’ as it doesn’t have any special meaning. Let’s see how we can create the same string using raw strings.

>>> s = r'Hi\xHello'
>>> print(s)
Hi\xHello

If you are on Python console and create a raw-string like below.

>>> r'Hi\xHello'
'Hi\\xHello'

Don’t get confused with the output having two backslashes. It’s just to show it as a normal python string where backslash is being escaped.

Python Raw String and Quotes

When a backslash is followed by a quote in a raw string, it’s escaped. However, the backslash also remains in the result. Because of this feature, we can’t create a raw string of single backslash. Also, a raw string can’t have an odd number of backslashes at the end. Some of the invalid raw strings are:

r'\'  # missing end quote because the end quote is being escaped
r'ab\\\'  # first two backslashes will escape each other, the third one will try to escape the end quote.

Let’s look at some of the valid raw string examples with quotes.

raw_s = r'\''
print(raw_s)

raw_s = r'ab\\'
print(raw_s)

raw_s = R'\\\"'  # prefix can be 'R' or 'r'
print(raw_s)

Output:

\'
ab\\
\\\"

That’s all for a quick introduction of python raw string.

You can checkout complete python script and more Python examples from our GitHub Repository.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

Sign up

Summary: in this tutorial, you will learn about Python raw strings and how to use them to handle strings that treat backslashes as literal characters.

Introduction to the Python raw strings

In Python, when you prefix a string with the letter r or R such as r'...' and R'...', that string becomes a raw string. Unlike a regular string, a raw string treats the backslashes (\) as literal characters.

Raw strings are useful when you deal with strings that have many backslashes, for example, regular expressions or directory paths on Windows.

To represent special characters such as tabs and newlines, Python uses the backslash (\) to signify the start of an escape sequence. For example:

s = 'lang\tver\nPython\t3' print(s)

Code language: Python (python)

Output:

lang ver Python 3

Code language: Python (python)

However, raw strings treat the backslash (\) as a literal character. For example:

s = r'lang\tver\nPython\t3' print(s)

Code language: Python (python)

Output:

lang\tver\nPython\t3

Code language: Python (python)

A raw string is like its regular string with the backslash (\) represented as double backslashes (\\):

s1 = r'lang\tver\nPython\t3' s2 = 'lang\\tver\\nPython\\t3' print(s1 == s2) # True

Code language: Python (python)

In a regular string, Python counts an escape sequence as a single character:

s = '\n' print(len(s)) # 1

Code language: Python (python)

However, in a raw string, Python counts the backslash (\) as one character:

s = r'\n' print(len(s)) # 2

Code language: Python (python)

Since the backslash (\) escapes the single quote (') or double quotes ("), a raw string cannot end with an odd number of backslashes.

For example:

s = r'\'

Code language: Python (python)

Error:

SyntaxError: EOL while scanning string literal

Code language: Python (python)

Or

s = r'\\\'

Code language: Python (python)

Error:

SyntaxError: EOL while scanning string literal

Code language: Python (python)

Use raw strings to handle file path on Windows

Windows OS uses backslashes to separate paths. For example:

c:\user\tasks\new

Code language: Python (python)

If you use this path as a regular string, Python will issue a number of errors:

dir_path = 'c:\user\tasks\new'

Code language: Python (python)

Error:

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \uXXXX escape

Code language: Python (python)

Python treats \u in the path as a Unicode escape but couldn’t decode it.

Now, if you escape the first backslash, you’ll have other issues:

dir_path = 'c:\\user\tasks\new' print(dir_path)

Code language: Python (python)

Output:

c:\user asks ew

Code language: Python (python)

In this example, the \t is a tab and \n is the new line.

To make it easy, you can turn the path into a raw string like this:

dir_path = r'c:\user\tasks\new' print(dir_path)

Code language: Python (python)

Convert a regular string into a raw string

To convert a regular string into a raw string, you use the built-in repr() function. For example:

s = '\n' raw_string = repr(s) print(raw_string)

Code language: Python (python)

Output:

'\n'

Code language: Python (python)

Note that the result raw string has the quote at the beginning and end of the string. To remove them, you can use slices:

s = '\n' raw_string = repr(s)[1:-1] print(raw_string)

Code language: Python (python)

Summary

  • Prefix a literal string with the letter r or R to turn it into a raw string.
  • Raw strings treat backslash as a literal character.

Did you find this tutorial helpful ?

How do you print raw strings in Python?

Python raw string is created by prefixing a string literal with 'r' or 'R'. Python raw string treats backslash (\) as a literal character. This is useful when we want to have a string that contains backslash and don't want it to be treated as an escape character.

What is a raw string in Python?

A Python raw string is a normal string, prefixed with a r or R. This treats characters such as backslash ('\') as a literal character. This also means that this character will not be treated as a escape character.

How do you convert a string to a raw string in Python?

Use the built-in function repr() to convert normal strings into raw strings. The string returned by repr() has ' at the beginning and the end. Using slices, you can get the string equivalent to the raw string.

How can we make a string tab a raw string?

Raw string literal in C++ The \n is used to return the cursor to the next line, the \t generates a tab etc. If we want to print these characters in the output without seeing the effect of them, we can use the raw string mode. To make a string to raw string we have to add "R" before the string.