检查函数输入是列表还是字符串的 Pythonic 方法

Pythonic way to check if a function input is a list or string

我想知道最符合 Python 风格的方法是检查函数输入是字符串还是列表。我希望用户能够输入字符串列表或字符串本身。

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

谢谢。

你的代码没问题。但是您提到该列表应该是一个字符串列表:

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

Check if input is a list/tuple of strings or a single string

第二种方法很好,除了它应该使用 print(string_) 而不是 print(input),如果重要的话:

def example(input):
    if isinstance(input,list):
       for string_ in input:
           print(string_)
           #do something with strings
    else:
        print(input)
        #do something with the single string


example(['2','3','4'])
example('HawasKaPujaari')

输出:

2
3
4
HawasKaPujaari