最近我收到了根据不同长度的元组动态格式化字符串的需求。其思想是根据元组值重复填充字符串,直到字符串格式化完成。例如,假设我的字符串格式如下:
"{} {} {} {} {} {}"
我想将内容插入到字符串中,例如:
# 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"
我在这里搜索但找不到任何好的方法来做到这一点,所以想在这里分享。
最佳答案
>>> 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'
关于python - 根据不同数量/长度的值/元组动态格式化字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40556990/