numberofrow, its value is dynamically set in form field.
now since numberofrow is in multiple tables, when i receive that variable from form,
if only one numerofrow, its a String, for ex. numberofrow = 01
if more than one numberofrow, its a list, for ex. numberofrow = [01, 02, 04]
Now how do i differentiate if its a list or string in my python code?
am thinking of using,
if type(numberofrow).__name__=='list':
#do this
else:
#do this
Thanks, Sunny.
For this purpose there is a build-in called isinstance. You can use it to check if an object is an instance of that class (and compared to your solution also super classes are considered in this test).
if isinstance(numberofrow, list):
# do this
else:
# do that
It's quite common to do something like isinstance(numberofrow, basestring). basestring is the super class of both string types in Python 2 - str and unicode - and the test will match both of them.
Alternatively, you can also provide a tuple of possible classes/types like isinstance(numberofrow, (list, tuple)). This test will succeed if the instance is either a instance of a list or a tuple.
What framework are you using to get that value from the form? A sensible one would definitely provide a way to return always a list -- specifically, if the value has been entered just once, a one-item list (and possibly, if the value has not been entered at all, an empty list).
For example, with good old cgi, you'd use the getlist method of the FieldStorage instance -- form.getlist('numberofrow') instead of form.getvalue('numberofrow') which behaves as you describe, returning either a string or a list -- and that would solve all your problems much more simply and elegantly!
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