Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

Given that strings act as lists of characters, how can I tell which kind the method has received?

I'd like to be able to accept either standard or unicode strings for a single entry, and either lists or tuples for multiple, so isinstance doesn't seem to be the answer unless I'm missing a clever trick with it (like taking advantage of common ancestor classes?).

Python version is 2.5

like image 559
mavnn Avatar asked May 28 '09 19:05

mavnn


People also ask

How do I check if a variable is a list or a string?

Check if Variable is a List with type() Now, to alter code flow programatically, based on the results of this function: a_list = [1, 2, 3, 4, 5] # Checks if the variable "a_list" is a list if type(a_list) == list: print("Variable is a list.") else: print("Variable is not a list.")

How do you check if it is a list or string in Python?

Python Find String in List using count() We can also use count() function to get the number of occurrences of a string in the list. If its output is 0, then it means that string is not present in the list. l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C'] s = 'A' count = l1.

How do you check if an input is in a tuple Python?

Method #1 : Using type() This inbuilt function can be used as shorthand to perform this task. It checks for the type of variable and can be employed to check tuple as well.

Is it a tuple or a list?

The key difference between the tuples and lists is that while the tuples are immutable objects the lists are mutable. This means that tuples cannot be changed while the lists can be modified.


1 Answers

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

like image 72
Steef Avatar answered Oct 26 '22 10:10

Steef