When create a python string, we can add u, r and b in front of it. In this tutorial, we will introduce the meaning of them and help you understand and use them.
str_u = u'这是一个测试string\n'
str_u is defined starting with u, which means str_u is a unicode string and is encoded by unicode.
When str_u contains some non-ascii characters, you shoud add u in the front of string.
str_b = b'this is a test string\n'
str_b is defined starting with b, which means str_b is a bytes type, it can be decode to a string.
str_r = r'this is a test string\n'
str_r is defined starting with r, which means characters in str_r can not be escaped, \n does not mean new line, only represents characters ‘\‘ and ‘n‘.
Print str_u, str_b and str_r.
print(type(str_u)) print(str_u) print(type(str_b)) print(str_b) print(type(str_r)) print(str_r)
Then the result is:
<class 'str'> 这是一个测试string <class 'bytes'> b'this is a test string\n' <class 'str'> this is a test string\n