简体   繁体   English

如何将不同数量的 arguments 从元组传递到 python 中的字符串格式?

[英]How to pass varying number of arguments from tuple to string format in python?

I am facing a difficulty in passing varying number of arguments from tuple to string format.我在将不同数量的 arguments 从元组传递到字符串格式时遇到了困难。 Sometimes my tuple consists of only one value, but sometimes up to 10 values.有时我的元组只包含一个值,但有时最多包含 10 个值。 If I want to print all of the values in print statement how do I do that?如果我想打印 print 语句中的所有值,我该怎么做? I have tried:我努力了:

tup = ('val1', 'val2', 'val3')
print('List consists of: {}'.format(*tup))

but it prints out only the first value.但它只打印出第一个值。 Unfortunately, each time I have varying number of arguments to print.不幸的是,每次我都要打印不同数量的 arguments。

Remove the * so you are not unpacking the tuple:删除 * 这样您就不会解包元组:

tup = ('val1', 'val2', 'val3')
print('List consists of: {}'.format(tup))

Output: Output:

List consists of: ('val1', 'val2', 'val3')

You don't need .format() or .join() in this case.在这种情况下,您不需要.format().join() Just pass *tup as agument to the print function:只需将*tup tup 作为参数传递给打印 function:

>>> tup = ('h', 'e', 'l', 'l', 'o', 'world')
>>> print(*tup)
h e l l o world

It works for number's too;它也适用于数字;

tup = (1, 2 ,3)

print('List consists of:', *tup)
[OUTPUT]: List consists of: 1 2 3

And you can add separators if you want;如果需要,您可以添加分隔符;

print('List consists of:', *tup, sep=', ')
[OUTPUT]: List consists of: 1, 2, 3

The special syntax *args ( *mystrings in our case) in function definitions in python is used to pass a variable number of arguments to a function. The special syntax *args ( *mystrings in our case) in function definitions in python is used to pass a variable number of arguments to a function. It is used to pass a non-keyworded, variable-length argument list .它用于传递非关键字、可变长度的参数列表

The nice thing here that they are passed as a tuple by python which make this a Classic and strait forward approach.这里的好处是它们作为tuple被 python 传递,这使得这是一种经典且严格的方法。 see this approach in the code snippet bellow:在下面的code snippet中看到这种方法:

def foo(*mystrings): ## which ofen used as *args
    for string in mystrings:
    print(string)    ## Or do what ever you want.

Now call it:现在调用它:

tup = ('val1', 'val2', 'val3')
foo(tup)

If you want just to construct a string from the tuple you can use join() method to do the job:如果你只想从tuple构造一个字符串,你可以使用join()方法来完成这项工作:

strt=' '.join(tup)

str.join(iterable) str.join(可迭代)

Return a string which is the concatenation of the strings in iterable.返回一个字符串,它是 iterable 中字符串的串联。 A TypeError will be raised if there are any non-string values in iterable, including bytes objects.如果 iterable 中有任何非字符串值,包括字节对象,则会引发 TypeError。 The separator between elements is the string providing this method.元素之间的分隔符是提供此方法的字符串。

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

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