最近我得到了根据不同长度的元组动态格式化字符串的要求。我们的想法是根据元组值重复填充字符串,直到字符串格式化完成。例如,假设我的字符串格式为:
"{} {} {} {} {} {}"
我想将内容插入字符串中,如:
# 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"
我在这里搜索过但找不到任何好办法,所以想在这里分享。
答案 0 :(得分:1)
>>> 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()
和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'