Skip to content Skip to sidebar Skip to footer

Check If Input Is A List/tuple Of Strings Or A Single String

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 strings. Give

Solution 1:

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:

ifisinstance(some_object, basestring):
    ...
elifall(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

Solution 2:

isinstanceis an option:

In [2]: isinstance("a", str)
Out[2]: True

In [3]: isinstance([], str)
Out[3]: False

In [4]: isinstance([], list)
Out[4]: True

In [5]: isinstance("", list)
Out[5]: False

Solution 3:

Type checking:

deffunc(arg):
    ifnotisinstance(arg, (list, tuple)):
        arg = [arg]
    # process

func('abc')
func(['abc', '123'])

Varargs:

def func(*arg):
    # process

func('abc')
func('abc', '123')
func(*['abc', '123'])

Solution 4:

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 compatibilityif'basestring'notinglobals():
   basestring = str

v = "xx"ifisinstance(v, basestring):
   print("is string")

Solution 5:

>>> type('abc') isstrTrue>>> type(['abc']) isstrFalse

This code is compatible with Python 2 and 3

Post a Comment for "Check If Input Is A List/tuple Of Strings Or A Single String"