python - 根据不同数量/长度的值/元组动态格式化字符串

标签 python string-formatting

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

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

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

# 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()来做到这一点和 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/

相关文章:

python - 在 Python 3 中打开 Python 2 Pickle 文件时出现 TypeError : a bytes-like object is required, 而不是 'str'

javascript - 如何在 javascript/jquery 事件后更改 Django 中的服务器端数据?

python - 如何通过两点(直径端)画圆?

使用 Stringformat 的 WPF 绑定(bind)行为与使用代码不同?

sql - 使用 rpad 填充 Postgresql 中的字符串而不截断它

python - 从旧 Python 版本到 Python 3 的高阶函数

python - 在 Pycharm : How to turn off interactive mode? 中调试时使用 Matplotlib

java - 如何在Java中编写连续命名的文件?

python - python2.6中将整数转换为格式化的二进制字符串

c - 格式字符串利用长度