For my program I have a lot of places where an object can be either a string or a list containing strings and other similar lists. These are generally read from a JSON file. They both need to be treated differently. Right now, I am just using isinstance, but that does not feel like the most pythonic way of doing it, so does anyone have a better way of doing it?
A string in python is an ordered sequence of characters. The point to be noted here is that a list is an ordered sequence of object types and a string is an ordered sequence of characters. This is the main difference between the two.
Strings and lists are similar, but they are not same and many people don't know the main difference between a string and a list in python. One simple difference between strings and lists is that lists can any type of data i.e. integers, characters, strings etc, while strings can only hold a set of characters.
The similarity between Lists and Strings in Python is that both are sequences. The differences between them are that firstly, Lists are mutable but Strings are immutable. Secondly, elements of a list can be of different types whereas a String only contains characters that are all of String type.
String[] is an array of Strings while ArrayList is a generic class which takes different types of objects (here it takes Strings). Therefore you can only perform normal array operations with String[].
No need to import modules, isinstance()
, str
and unicode
(versions before 3 -- there's no unicode
in 3!) will do the job for you.
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> isinstance(u'', (str, unicode)) True >>> isinstance('', (str, unicode)) True >>> isinstance([], (str, unicode)) False >>> for value in ('snowman', u'☃ ', ['snowman', u'☃ ']): ... print type(value) ... <type 'str'> <type 'unicode'> <type 'list'>
Python 3.2 (r32:88445, May 29 2011, 08:00:24) [GCC 4.2.1 (Apple Inc. build 5664)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> isinstance('☃ ', str) True >>> isinstance([], str) False >>> for value in ('snowman', '☃ ', ['snowman', '☃ ']): ... print(type(value)) ... <class 'str'> <class 'str'> <class 'list'>
From PEP008:
Object type comparisons should always use
isinstance()
instead of comparing types directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With