Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell if a python variable is a string or a list?

I have a routine that takes a list of strings as a parameter, but I'd like to support passing in a single string and converting it to a list of one string. For example:

def func( files ):     for f in files:         doSomethingWithFile( f )  func( ['file1','file2','file3'] )  func( 'file1' ) # should be treated like ['file1'] 

How can my function tell whether a string or a list has been passed in? I know there is a type function, but is there a "more pythonic" way?

like image 777
Graeme Perrow Avatar asked May 07 '09 18:05

Graeme Perrow


People also ask

How do you check if something is a list Python?

Given an object, the task is to check whether the object is list or not. if isinstance (ini_list1, list ): print ( "your object is a list !" )

How do I check if a variable is a string?

Use the typeof operator to check if a variable is a string, e.g. if (typeof variable === 'string') . If the typeof operator returns "string" , then the variable is a string. In all other cases the variable isn't a string. Copied!

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

To check if a variable contains a value that is a string, use the isinstance built-in function. The isinstance function takes two arguments. The first is your variable. The second is the type you want to check for.

How do I know the type of a variable in Python?

To get the type of a variable in Python, you can use the built-in type() function. In Python, everything is an object. So, when you use the type() function to print the type of the value stored in a variable to the console, it returns the class type of the object.


2 Answers

isinstance(your_var, basestring) 
like image 143
Ayman Hourieh Avatar answered Sep 29 '22 02:09

Ayman Hourieh


Well, there's nothing unpythonic about checking type. Having said that, if you're willing to put a small burden on the caller:

def func( *files ):     for f in files:          doSomethingWithFile( f )  func( *['file1','file2','file3'] ) #Is treated like func('file1','file2','file3') func( 'file1' ) 

I'd argue this is more pythonic in that "explicit is better than implicit". Here there is at least a recognition on the part of the caller when the input is already in list form.

like image 37
David Berger Avatar answered Sep 29 '22 01:09

David Berger