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

前端 未结 9 1193
执念已碎
执念已碎 2020-12-24 05:13

I\'ve a method that I want to be able to accept either a single string (a path, but not necessarily one that exists on the machine running the code) or a list/tuple of strin

9条回答
  •  囚心锁ツ
    2020-12-24 05:31

    You can check if a variable is a string or unicode string with

    • Python 3:
        isinstance(some_object, str)
    
    • Python 2:
        isinstance(some_object, basestring)
    

    This will return True for both strings and unicode strings

    As you are using python 2.5, you could do something like this:

    if isinstance(some_object, basestring):
        ...
    elif all(isinstance(item, basestring) 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
    

    Stringness is probably not a word, but I hope you get the idea

提交回复
热议问题