根据 values/tuples 的 number/length 动态格式化字符串

Dynamically format string based on varying number/length of values/tuples

最近我接到了根据不同长度的元组动态格式化字符串的需求。思路是根据元组值重复填充字符串,直到字符串格式化完成。例如,假设我的字符串格式为:

"{} {} {} {} {} {}"

我想将内容插入到字符串中,如:

# For: ("hello",)
'hello hello hello hello hello'  # <- repeated "hello"

# For: ("hello", "world")
'hello world hello world hello'  # <- repeated "hello world"

# For: ("hello", "world", "2017")
'hello world 2017 hello world'   # <- repeated "hello world 2017"

我在这边搜了一下,没有找到好的方法,所以想在这里分享一下。

使用itertools.chain():

>>> from itertools import chain

>>> my_string = "{} {} {} {} {}"
>>> my_tuple = ("hello", "world")  # tuple of length 2
>>> my_string.format(*chain(my_tuple*6)) # here 6 is some value equal to
'hello world hello world hello'          # maximum number of time for which
                                         # formatting is allowed

或者,我们也可以使用 itertools.chain.from_iterator() and itertools.repeat() 作为:

>>> from itertools import chain, repeat

>>> my_string.format(*chain.from_iterable(repeat(my_tuple, 6)))
'hello world hello world hello'

元组将不断重复自身,直到填满所有格式字符串。


其他几个样本运行:

# format string of 5
>>> my_string = "{} {} {} {} {}"

### Tuple of length 1
>>> my_tuple = ("hello",)
>>> my_string.format(*chain(my_tuple*6))
'hello hello hello hello hello'

### Tuple of length 2
>>> my_tuple = ("hello", "world")
>>> my_string.format(*chain(my_tuple*6))
'hello world hello world hello'

### Tuple of length 3
>>> my_tuple = ("hello", "world", "2016")
>>> my_string.format(*chain(my_tuple*6))
'hello world 2016 hello world'