简体   繁体   English

Python字符串.format(* variable)

[英]Python string .format(*variable)

I'm reading a book to read and it covers this below example. 我正在读一本书来阅读,它涵盖了下面的例子。

somelist = list(SPAM)
parts = somelist[0], somelist[-1], somelist[1:3]
'first={0}, last={1}, middle={2}'.format(*parts)

Everything seems clear apart from the star being used at the end of the last line. 除了在最后一行末尾使用的星星之外,一切看起来都很清楚。 The book fails to explain the usage of this and I hate to progress on without full understanding things. 这本书没有解释这个用法,我讨厌在没有完全理解的情况下继续前进。

Many thanks for your help. 非常感谢您的帮助。

The * operator, often called the star or splat operator, unpacks an iterable into the arguments of the function, so in this case, it's equivalent to: *运算符(通常称为star或splat运算符)将iterable解包为函数的参数,因此在这种情况下,它等效于:

'first={0}, last={1}, middle={2}'.format(parts[0], parts[1], parts[2])

The python docs have more info. python文档有更多信息。

It's argument unpacking (kinda) operator. 它是解包(有点)运算符的参数。

args = [1, 2, 3]
fun(*args)

is the same as 是相同的

fun(1, 2, 3)

(for some callable fun ). (为了一些可赎回的fun )。

There's also star in function definition, which means "all other positional arguments": 函数定义中也有星号,这意味着“所有其他位置参数”:

def fun(a, b, *args):
    print('a =', a)
    print('b =', b)
    print('args =', args)

fun(1, 2, 3, 4) # a = 1, b = 2, args = [3, 4]

关于单和双星号形式的综合解释

* when used inside a function means that the variable following the * is an iterable, and it extracted inside that function. *在函数内部使用时意味着*variable是可迭代的,并且在该函数内部提取。 here 'first={0}, last={1}, middle={2}'.format(*parts) actually represents this: 这里'first={0}, last={1}, middle={2}'.format(*parts)实际上代表了这个:

'first={0}, last={1}, middle={2}'.format(parts[0],parts[1],parts[2])

for example: 例如:

 >>> a=[1,2,3,4,5]
 >>> print(*a)
 1 2 3 4 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM