[英]How can I put two arguments in one string for a input function in python?
[英]How can I pass a user input string to a function as arguments in a python script?
我想使用空格分隔的單詞作為參數,將用戶輸入字符串傳遞給函數。 但是,造成這個問題的原因是我不知道用戶會給出多少個參數。
def your_function(*args):
# 'args' is now a list that contains all of the arguments
...do stuff...
input_args = user_string.split()
your_function(*input_args) # Convert a list into the arguments to a function
http://docs.python.org/tutorial/controlflow.html#arbitrary-argument-lists
當然,如果您是設計函數的人,則可以將其設計為將列表作為單個參數接受,而不需要單獨的參數。
使用str.split和參數解壓縮的簡單方法:
f(*the_input.split(' '))
但是,這不會執行任何轉換(所有參數仍然是字符串),並且split有一些警告(例如'1,,2'.split(',') == ['1', '', '2']
;請參閱文檔)。
有兩個選擇。 您可以使函數采用參數列表:
def fn(arg_list):
#process
fn(["Here", "are", "some", "args"]) #note that this is being passed as a single list parameter
或者,您可以在任意參數列表中收集參數:
def fn(*arg_tuple):
#process
fn("Here", "are", "some", "args") #this is being passed as four separate string parameters
在這兩種情況下, arg_list
和arg_tuple
幾乎相同,唯一的區別是一個是列表,另一個是元組: ["Here, "are", "some", "args"]
或("Here", "are", "some", "args")
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.