Python字符串前的'r'

Python字符串前的r


最近学习python发现字符串前面会多出一个‘r’,不解。网上查询和自己测试了下:

加上‘r’,是让字符串不转义,这样可以保留原始的字符串,

如:

>>> filepath='D:\IStudy\Python\program_test\2017-05-10.txt'
>>> print(os.path.basename(filepath))

program_test  7-05-10.txt

而如果加上‘r’

>>> filepath=r'D:\IStudy\Python\program_test\2017-05-10.txt'
>>> print(os.path.basename(filepath))

D:\IStudy\Python\program_test  2017-05-10.txt

文档中reference.pdf中是这么解释的:

Both string and bytes literals may optionally be prefixed with a letter ’r’ or ’R’; such strings are called raw strings
and treat backslashes as literal characters;

那么‘D:\\dir’与r‘D:\dir’是等价的!



发布了96 篇原创文章 · 获赞 22 · 访问量 31万+

猜你喜欢

转载自blog.csdn.net/chuan_day/article/details/72457165