使用 kwargs 时,如何以 Python 格式()转义冒号? [英] How do I escape a colon in Python format() when using kwargs?

查看:16
本文介绍了使用 kwargs 时,如何以 Python 格式()转义冒号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本字典,我想打印一个键中带有冒号的字典.不幸的是,冒号字符用于格式化,所以我需要以某种方式对其进行转义.

例如:

<预><代码>>>>d = {'hello': 'world', 'with:colon': 'moo'}>>>'{你好}'.format(**d)'世界'>>>'{with:colon}'.format(**d)KeyError: 'with'>>>'{with\:colon}'.format(**d)KeyError: 'with\\'>>>'{with::colon}'.format(**d)KeyError: 'with'

解决方案

作为一种解决方法:

<预><代码>>>>d = {'hello': 'world', 'with:colon': 'moo'}>>>'{hello} {}'.format(d['with:colon'],**d)'世界喵'>>>'{hello} {0}'.format(d['with:colon'],**d)'世界喵'

I have a dictionary with a colon in a key that I wish to print. Unfortunately the colon character is used for formatting, so I need to somehow escape it.

For example:

>>> d = {'hello': 'world', 'with:colon': 'moo'}

>>> '{hello}'.format(**d)
'world'

>>> '{with:colon}'.format(**d)
KeyError: 'with'

>>> '{with\:colon}'.format(**d)
KeyError: 'with\\'

>>> '{with::colon}'.format(**d)
KeyError: 'with'

解决方案

As a workaround:

>>> d = {'hello': 'world', 'with:colon': 'moo'}
>>> '{hello} {}'.format(d['with:colon'],**d)
'world moo'
>>> '{hello} {0}'.format(d['with:colon'],**d)
'world moo'

这篇关于使用 kwargs 时,如何以 Python 格式()转义冒号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆