python:可变字符串格式

python: variable string formatting

我有如下字符串:

a = "This is {} code {}"

在我的代码的后面部分,我将使用提供给以下函数的参数来格式化字符串:

def format_string(str, *args):
    fmt_str = str.format(*args)
    print fmt_str
    ...

我的问题是,如果提供给函数 format_string 的 args 数量少于或多于要求,我会得到一个异常。 相反,如果 args 较少,我希望它打印空 {} 并且如果 args 超过要求,那么我希望忽略额外的 args。 我试过用几种方法来做到这一点,但无法避免异常。有人可以帮忙吗?

更新:我能够根据此 post 中提供的答案解决此问题: Leaving values blank if not passed in str.format

这是我的实现:

class BlankFormatter(Formatter):
    def __init__(self, default=''):
        self.default = default
    def get_value(self, key, args, kwargs):
        if isinstance(key, (int, long)):
            try:
                return args[key]
            except IndexError:
                return ""
        else:
            return kwargs[key]

必须按如下方式修改字符串才能使用上面的 BlankFormatter:

a = "This is {0} code {1}"

在我的 format_string 函数中,我使用 BlankFormatter 来格式化字符串:

def format_string(str, *args):
    fmt = BlankFormatter()
    fmt_str = fmt.format(str,*args)
    print fmt_str
    ...
def formatter(input, *args):
    format_count = input.count("{}")
    args = list(args) + ["{}"] * (format_count - len(args))
    print input.format(*args[:format_count])

formatter("{} {} {}", "1", "2")
formatter("{} {} {}", "1", "2", "3")
formatter("{} {} {}", "1", "2", "3", "4")

1 2 {}
1 2 3
1 2 3

有几种不同的方法可以做到这一点,其中一些或多或少是灵活的。也许这样的事情对你有用:

from __future__ import print_function


def transform_format_args(*args, **kwargs):
    num_args = kwargs['num_args']  # required
    filler = kwargs.get('filler', '')  # optional; defaults to ''

    if len(args) < num_args:  # If there aren't enough args
        args += (filler,) * (num_args - len(args))  # Add filler args
    elif len(args) > num_args:  # If there are too many args
        args = args[:num_args]  # Remove extra args

    return args


args1 = transform_format_args('cool', num_args=2)
print("This is {} code {}.".format(*args1))  # This is cool code .

args2 = transform_format_args('bird', 'worm', 'fish', num_args=2)
print("The {} ate the {}.".format(*args2))  # The bird ate the worm.

args3 = transform_format_args(num_args=3, filler='thing')
print("The {} stopped the {} with the {}.".format(*args3))
# The thing stopped the thing with the thing.

num_args是你要的args个数,不是你传入的个数。filler是不够用args .