python cook it

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值