星号 `*` 在 Python 3 中的字符串格式化方法 `.format(*) ` 中如何工作? [英] How does an asterisk `*` work in the string formatting method `.format(*) ` in Python 3?

查看:49
本文介绍了星号 `*` 在 Python 3 中的字符串格式化方法 `.format(*) ` 中如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

什么是**(双星/asterisk) 和 * (star/asterisk) 用于参数吗?

sum_string = "18"new_string = "这是一个新的字符串值{}"print(new_string.format(sum_string)) #它提供值18的输出print(new_string.format(*sum_string)) #它提供值1的输出

解决方案

format无关.* 解压参数,因此如果列表中有 4 个占位符和 4 个元素,则 format 解压参数并填充插槽.示例:

args = range(4)打印(("{}_"*4).格式(*args))

印刷品:

0_1_2_3_

在您的第二种情况下:

print(new_string.format(*sum_string))

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

通过几个占位符,您会看到这一点:

<预><代码>>>>args = "abcd">>>打印("{}_{}_{}_{}").format(*args))A B C D

What is the use of * in .format(*)? When using it in the format function below print(new_string.format(*sum_string)) it changes the value of sum_string in the output from 18 to 1 Why does that happen? I have read the following link about *args and **kwargs but couldn't understand how does that apply to the .format() function

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

解决方案

it has nothing to do with format. * unpacks the arguments so if there are, say 4 placeholders and 4 elements in your list, then format unpacks the args and fills the slots. Example:

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

prints:

0_1_2_3_

In your second case:

print(new_string.format(*sum_string))

the arguments to unpack are the characters of the string (the string is seen as an iterable by the argument unpacking), and since there's only one placeholder, only the first character is formatted & printed (and as opposed to warnings you could get with C compilers and printf, python doesn't warn you about your list of arguments being too long, it just doesn't use all of them)

With several placeholders you'd witness this:

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

这篇关于星号 `*` 在 Python 3 中的字符串格式化方法 `.format(*) ` 中如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆