Pythonic的方法来检查函数的输入是否是列表或字符串
Pythonic的方法来检查函数的输入是否是列表或字符串
这个问题已经有了答案:
我想知道检查一个函数输入是字符串还是列表的最pythonic的方法。我希望用户能够输入一个字符串列表或单个字符串。
def example(input): for string in input: #Do something here. print(string)
显然,如果输入是字符串列表,这将起作用,但如果输入是单个字符串,则不起作用。这里最好的做法是在函数本身中添加类型检查吗?
def example(input): if isinstance(input,list): for string in input: print(input) #do something with strings else: print(input) #do something with the single string
谢谢。
admin 更改状态以发布 2023年5月23日
您的代码没问题。但是您提到列表应该是一个字符串列表:
if isinstance(some_object, str): ... elif all(isinstance(item, str) for item in some_object): # check iterable for stringness of all items. Will raise TypeError if some_object is not iterable ... else: raise TypeError # or something along that line