Exploring string prefixes in Python

10/08/2020


1. the r prefix
When an 'r' or 'R' prefix is present, a character following a backslash is included in the string without change, and all backslashes are left in the string. This prefix can be used for representing
> file-paths
fpath = "C:/Users/Desktop/File.py"
> and URLs.
url = "https://getbootstrap.com/docs/4.0/content/code/"
NOTE: A 'u' or 'b' prefix may be followed by an 'r' prefix.

2. the b prefix
The 'b' prefix signifies a bytes string literal.
If you see it used in Python 3 source code, the expression creates a bytes object, not a regular Unicode str object. If you see it echoed in your Python shell or as part of a list, dict or other container contents, then you see a bytes object represented using this notation.
>>> s = b'bytestr'
>>> type(s)
<class 'bytes'>


2. the u prefix
A prefix of 'u' or 'U' makes the string a Unicode string. Unicode strings use the Unicode character set as defined by the Unicode Consortium and ISO 10646. An example of a unicode usecase is printing non english alphabet characters.
>>> s = u'\u0420\u043e\u0441\u0441\u0438\u044f'
'Россия'


Reference: More on string literals

    I'm Social, Let's connect: