None + "123"
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
避免方式:不确定的情况下,字符创相加,可以 str 一下
c = [1]
c[2]
IndexError: list index out of range
IndexError: list index out of range
主观避免:在使用时应确保 k < len(c)
d = {"a": 1}
d["b"]
KeyError: 'b'
KeyError: 'b'
避免方式,在不确定的情况下,使用 d.get("b", 0) ,使用get 并且设置默认值
使用types 库,这里面是一些python的 所有类型
import types
if isinstance(1, types.IntType):
# do something
出现下面的错误:
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\IPython\core\interactiveshell.py", line 3035, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-44-093f7e45c18c>", line 1, in <module>
test("123", **{"a": 1})
TypeError: test() got multiple values for keyword argument 'a'
可以这样产生:
def test(a, **kwargs):
print a
print kwargs
test("123", **{"a":1})
这样就会出现上面的错误了。原因是**解包的时候,有了关键字参数a,和位置参数a重复了,获取了多个值
可以像下面的这样:
def test(*args, **kwargs):
print args
print kwargs
test("123", **{"a": 1})
一个BUG:
问题:判断一个字符串是否使用and单词进行分割,如果分割,则进行一些操作
看到的程序中的做法是直接使用下面的方式:
s = ""
if and in s:
# do something
pass
然后在线上环境就出错了,找了一些原因,原来是字符创中有类似的 hand 的这样的单词,在判断的时候条件为真,就进入了一个不期望的代码块中。
判断是否使用and单词可以使用下面的方式:(单词一般是用空格隔开的) \s+and\s+
import re
s = "hand"
p = "\s+and\s+"
if re.search(p, s):
print yes
else:
print no
s = "a and b"
if re.search(p, s):
print yes
本文探讨了Python编程中常见的错误类型,包括类型错误、索引错误、键错误等,并提供了预防和解决这些错误的有效策略。同时,文章还介绍了如何正确处理字符串分割问题,以及正则表达式的使用技巧。
1248

被折叠的 条评论
为什么被折叠?



