Python 根据不同数量/长度的值/元组动态设置字符串格式

Python 根据不同数量/长度的值/元组动态设置字符串格式,python,string-formatting,Python,String Formatting,最近,我得到了一个需求,即根据不同长度的元组动态格式化字符串。其思想是根据元组值重复填充字符串,直到字符串格式化完成。例如,假设我的字符串的格式为: "{} {} {} {} {} {}" 我想将内容插入字符串,如下所示: # For: ("hello",) 'hello hello hello hello hello' # <- repeated "hello" # For: ("hello", "world") 'hello world hello world hello' #

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

"{} {} {} {} {} {}"
我想将内容插入字符串,如下所示:

# 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"
#For:(“你好”,)
“你好”#使用:

或者,我们也可以使用和作为:

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


其他几个示例运行:

# 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'

与其乘以元组,还可以使用
chain.from_iterable(repeat(my_tuple))
@AlexHall在执行
my_string.format(*chain.from_iterable(repeat(my_tuple)))
时,我的控制台被冻结。检查了2.7和3,无论它如何指定
'n'
时间元组的数量应该像
repeat(我的元组,4)
oops一样重复,都没有想到当人们尝试将它转换成
格式时会发生什么。事实上,它试图扩展一个无限的iterable,但显然失败了。您还需要
islice
,哪种方法不符合这一点。@Alexall不需要
islice()
,因为
repeat()
有一个参数作为
times
,它限制迭代器限制重复。
>>> 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'