20180714 错题多转自www.fishc.com
1. file1 = open('C:\windows\temp\readme.txt', 'r') 表示以只读方式打开“C:\windows\temp\readme.txt”这个文本文件,但事实上这个语句会报错,知道为什么吗?你会如何修改?
会报错是因为在字符串中,我们约定“\t”和“\r”分别表示“横向制表符(TAB)”和“回车符”(详见:http://bbs.fishc.com/thread-92997-1-1.html),因此并不会按照我们计划的路径去打开文件。
Python 为我们铺好了解决的道路,只需要使用原始字符串操作符(R或r)即可
2.关于python3.6 字符串最后一位是的情况:
str1 = r'''#¥@#%……*¥(%\'''
会报错,原因在于:
http://docs.python.org/reference/lexical_analysis.html
String quotes can be escaped with a backslash, but the backslash remains in the string; for example, r"\"" is a valid string literal consisting of two characters: a backslash and a double quote; r"\" is not a valid string literal (even a raw string cannot end in an odd number of backslashes). Specifically, a raw string cannot end in a single backslash (since the backslash would escape the following quote character).
应该改为:
str1 = (r'#¥@#%……*¥(%''\\')
另外针对于列表中最后一位是\的情况比较麻烦,就目前还不能解决最后一位是\的情况,除非和列表其他项互换。
希望有知道转译列表中最后一位\方法的大神指点一二。