Home » Python

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?
Submitted by Sapna Deraje Radhakrishna, on March 04, 2020

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. 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.

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.

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

s='Hi\nHello'
print(s)

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

Output

Hi
Hello
Hi\nHello

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

s='Hi\xHello'

Output

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

Output

Hi\xHello
ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.