python - 星号 `*` 在 Python 3 的字符串格式化方法 `.format(*) ` 中如何工作?

标签 python python-3.x string-formatting args string.format

.format(*)中的*有什么用? 在 print(new_string.format(*sum_string)) 下面的格式函数中使用它时,它会将输出中的 sum_string 的值从 18 更改为 1 为什么会这样? 我已阅读以下有关 *args**kwargs 的链接,但无法理解它如何应用于 .format() 函数

What does ** (double star/asterisk) and * (star/asterisk) do for parameters?

sum_string = "18"
new_string = "This is a new string of value {}"

print(new_string.format(sum_string)) #it provides an output of value 18
print(new_string.format(*sum_string)) #it provides an output of value 1

最佳答案

它与格式无关。 * 解压参数,所以如果列表中有 4 个占位符和 4 个元素,则 format 解压参数并填充插槽。示例:

args = range(4)
print(("{}_"*4).format(*args))

打印:

0_1_2_3_

在你的第二种情况下:

print(new_string.format(*sum_string))

解包的参数是字符串的字符(字符串被解包参数视为可迭代的),并且由于只有一个占位符,因此只有第一个字符被格式化和打印(与使用 C 编译器和 printf 可能会收到的警告相反,python 不会警告您参数列表太长,它只是不会使用所有参数)

如果有多个占位符,您会看到这一点:

>>> args = "abcd"
>>> print("{}_{}_{}_{}").format(*args))
a_b_c_d

关于python - 星号 `*` 在 Python 3 的字符串格式化方法 `.format(*) ` 中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52475322/

相关文章:

Python 3 - 在 str.format() 中使用元组

python - 向 urllib.request.read 传递字符串但获取字节属性错误

python - 将表情符号视为正则表达式中的一个字符

python - 如果进程通过 paramiko ssh session 运行并且最后以 "&"运行,则进程终止

java - 获取 Formatter.format() String 中占位符的数量

javascript - 在 Javascript 中使用变量格式化字符串模板

python - 尝试在 tf.estimator 中使用 MirroredStrategy 时出错

python - 将 lambda 表达式转换为简单函数

python - 在python中计算范围内的用户输入数字

python - 在 Python 3 中捕获特定的 OSError 异常