What exactly do 'u' and 'r' string flags do, and what are raw string literals in Python?

Here, we are going to learn what exactly do 'u' and 'r' string flags do, and what are raw string literals in Python?
By Sapna Deraje Radhakrishna Last updated : January 03, 2024

Prefix of 'u' with a string

The prefix of 'u' in a string denotes the value of type Unicode rather than string (str). However, the Unicode strings are no longer used in Python3. The prefix of 'u' in a string denotes the value of type Unicode rather than str. However, the Unicode strings are no longer used in Python3. 

In Python2, if we type a string literal without 'u' in front, we get the old str type which stores 8-bit characters, and with 'u' in front we get the newer Unicode type that can store any Unicode character.

Prefix of 'r' with a string

Additionally adding 'r' doesn't change the type of the literal, just changes how the string literal is interpreted. Without the 'r' backlashes (/) are treated as escape characters. With 'r' (/) are treated as literal.

Raw strings

Prefixing the string with 'r' makes the string literal a 'raw string'. Python raw string treats backslash (\) as a literal character, which makes it useful when we want to have a string that contains backslash and don’t want it to be treated as an escape character.

Example 1

Consider the below example, where (\) has a special meaning.

s='Hi\nHello'
print(s)

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

Output

The output of the above example is:

Hi
Hello
Hi\nHello

Example 2

Consider the below example, where (\) doesn't have special meaning,

s='Hi\xHello'

Output

The output of the above example is:

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

Example 3

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

Output

The output of the above example is:

Hi\xHello

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.