相关疑难解决方法(0)

如何让Python优雅地格式化None和不存在的字段

如果我用Python写:

data = {'n': 3, 'k': 3.141594, 'p': {'a': 7, 'b': 8}}
print('{n}, {k:.2f}, {p[a]}, {p[b]}'.format(**data))
del data['k']
data['p']['b'] = None
print('{n}, {k:.2f}, {p[a]}, {p[b]}'.format(**data))
Run Code Online (Sandbox Code Playgroud)

我明白了:

3, 3.14, 7, 8
Traceback (most recent call last):
  File "./funky.py", line 186, in <module>
    print('{n}, {k:.2f}, {p[a]}, {p[b]}'.format(**data))
KeyError: 'k'
Run Code Online (Sandbox Code Playgroud)

而不是错误消息,我如何让Python更优雅地格式化None和不存在的字段?

举个例子,我想在输出中看到更像:

3, 3.14, 7, 8
3, ~, 7, ~
Run Code Online (Sandbox Code Playgroud)

当然,理想情况下,我希望能够指定使用的字符串而不是那些缺少的值.

python string-formatting missing-data

28
推荐指数
3
解决办法
2万
查看次数

多字符串格式

给定ints 的字典,我正在尝试使用每个数字格式化字符串,以及项目的复数形式.

样本输入dict:

data = {'tree': 1, 'bush': 2, 'flower': 3, 'cactus': 0}
Run Code Online (Sandbox Code Playgroud)

样本输出str:

'My garden has 1 tree, 2 bushes, 3 flowers, and 0 cacti'
Run Code Online (Sandbox Code Playgroud)

它需要使用任意格式的字符串.

我提出的最佳解决方案是PluralItem存储两个属性的类n(原始值),s('s'如果是复数''则为字符串,否则为空字符串).对不同的复数方法进行了分类

class PluralItem(object):
    def __init__(self, num):
        self.n = num
        self._get_s()
    def _get_s(self):
        self.s = '' if self.n == 1 else 's'

class PluralES(PluralItem):
    def _get_s(self):
        self.s = 's' if self.n == 1 else 'es'

class PluralI(PluralItem):
    def …
Run Code Online (Sandbox Code Playgroud)

python string customization string-formatting

22
推荐指数
4
解决办法
2万
查看次数