What Is The Difference Between R & U Flag At Python String Beginning

When you use python string, you may notice that some string start with 'u' or 'r' flag character. This two flag character will make the string behave differently. This article will give you some examples.

1. String Start With u Flag.

u flag indicate that the string content is unicode text. The special character in this string need to be escaped. For example ‘\n’ need to be translated to a new line. Let us look at below example.

# the unique code string contains '\n' character.
>>> str_1 = u'python \n is good'

# the u flag will not be printed out as part of the original string.
>>> str_1
'python \n is good'

# when print above string in console, the \n character means a new line.
>>> print(str_1)
python 
 is good

2. String Start With r Flag.

If you useĀ  r flag at the beginning of string definition, it means the string content is raw string literals, it will tell the python interpreter not to escape the special characters in the string start with ‘\’. Just keep the ‘\’ character in the string.

# below string contains '\n' character
>>> str_1 = r'python \n is good'

>>> str_1
'python \\n is good'

# because r flag, the '\n' character is not escaped.
>>> print(str_1)
python \n is good
>>> 

3. r vs u Flag.

r flag is very useful when you use regular expression in python development especially in Django url pattern mapping configuration. This flag can remove redundant ‘\’ in the url mapping string to simplify the url string.

Url regular expression without r flag:

'\\[email protected]\\w+.\\w+'

Url regular expression start with r flag:

r'\[email protected]\w+.\w+'
READ :   How To Use Matplotlib In Python And Ipython To Draw Single Line Plot Example

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.