python - Python 中的 KeyError **kwargs

标签 python python-3.x

只有第一个打印命令有效。我不知道为什么。我想根据传入的内容显示不同的前缀和后缀。

# We are going to have a word and a prefix or a suffix before or after
# that word

def joinWords(string, **sFox):
    if sFox['prefix']: 
        return sFox['prefix'] + string
    elif sFox['suffix']: 
        return string + sFox['suffix']
    return string




#Why does this work?
#print(joinWords("Cookie", prefix="sugar"))

#And this does not?
#print(joinWords("Cookie", suffix="monster"))

最佳答案

您遇到的问题是,kwargs 不会包含未指定的键。当您尝试索引一个不存在的字典键时,它会引发一个KeyError

最直接的解决方案是在尝试访问之前检查 key 是否存在:

    if 'prefix' in sFox and sFox['prefix']:

还有更好的 Pythonic 方式来做到这一点。如前所述,dict.get() 是一个不错的默认值选项:

    if sFox.get('prefix'):

这样,如果 prefix' 不在字典中,则该值将为 None,其计算结果为 bool 值 false 并完美地实现了这一目的。

当然,如果你真的不需要随机关键字参数,试试默认参数:

def joinWords(string, prefix=None, suffix=None):
    if prefix:
        return prefix + string
    elif suffix: 
        return string + suffix
    return string

IMO 这可能是一个更好的解决方案,除非您正在尝试了解关键字参数包。

关于python - Python 中的 KeyError **kwargs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53128068/

相关文章:

python - 类型错误 : unorderable types: Node() < Node()

python - 如何覆盖 Python 的 'str' 以便它返回大写值?

python - 如何改进带有不同颜色和字体文本的图像的 OCR?

python - 是否有比 'title' 更好的字符串方法来将字符串中的每个单词大写?

python - f 字符串不支持行连接吗?

python - 将 python 项目与虚拟环境相关联

python-3.x - 绑定(bind)方法的 MyPy 类型注释?

python - 统一码编码错误 : 'ascii' codec can't encode character in print function

python - 列表与列表列表的第一个元素之间的交集

python - 属性错误 : module 'cv2.cv2' has no attribute 'TrackerMOSSE_create'