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

前端 未结 9 1195
执念已碎
执念已碎 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

    Type checking:

    def func(arg):
        if not isinstance(arg, (list, tuple)):
            arg = [arg]
        # process
    
    func('abc')
    func(['abc', '123'])
    

    Varargs:

    def func(*arg):
        # process
    
    func('abc')
    func('abc', '123')
    func(*['abc', '123'])
    
    0 讨论(0)
  • 2020-12-24 05:32

    Can't you do:

    (i == list (i) or i == tuple (i))
    

    It would reply if the input is tuple or list. The only issue is that it doesn't work properly with a tuple holding only one variable.

    0 讨论(0)
  • 2020-12-24 05:43

    As I like to keep things simple, here is the shortest form that is compatible with both 2.x and 3.x:

    # trick for py2/3 compatibility
    if 'basestring' not in globals():
       basestring = str
    
    v = "xx"
    
    if isinstance(v, basestring):
       print("is string")
    
    0 讨论(0)
提交回复
热议问题