[英]My function for some reason auto-converts a string into a tuple?
I'm very confused here. 我在这里很困惑。 I'm trying to pass an optional string parameter to my function, but once the parameter is added, it converts the string to a tuple? 我正在尝试将可选的字符串参数传递给我的函数,但是一旦添加了参数,它将把字符串转换为元组吗? How can I stop it from doing that or convert back? 我怎样才能阻止它这样做或转换回来?
I have this: 我有这个:
def fen2grid(note, *optional)
print(optional)
# here it does other stuff
With this when I call it: 当我称呼它时:
fen2grid(example, '.')
now... the print is supposed to print a period. 现在...该打印应该打印一段。 Just . 只是。 This is just a test before I use it in the function and it seems to be a good thing that I'm testing it.What it prints is 这只是我在函数中使用它之前的一个测试,正在测试它似乎是一件好事。
('.',) ('。',)
I need the period because I need to work with that (it can be any other symbol too) 我需要句号,因为我需要使用它(也可以是任何其他符号)
Any help would be appreciated! 任何帮助,将不胜感激!
*args
reads an arbitrary number of arguments and encloses them as a tuple. *args
读取任意数量的参数并将其括为一个元组。 To access them you can simply do print(args[0])
or [print(x) for x in args]
要访问它们,您只需执行print(args[0])
或[print(x) for x in args]
Edit: Keep in mind that neither args or kwargs are keywords, you can replace them for any other placeholder preceded by * or ** 编辑:请记住,args或kwargs都不是关键字,您可以将它们替换为*或**之前的任何其他占位符
I'm trying to pass an optional string parameter to my function 我正在尝试将可选的字符串参数传递给函数
*optional
isn't quite how you do that. *optional
不是您如何做到的。 At least not for default/keyword argument like you are trying to use. 至少不像您尝试使用的default / keyword参数那样。 That is a tuple . 那是一个元组 。
Try 尝试
def fen2grid(note, optional=None)
print(optional)
For more details, see about Defining Functions . 有关更多详细信息,请参见有关定义函数 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.