0

I've made an html page that has several checkboxes. Each value of a checkbox are two numbers separated by a question mark sign, i.e. "1?16".

<input class="checkbox1" type="checkbox"  name ="nr_ids" id="checkbox_id" value ="1?16">Name1,16</label> <br>
<input class="checkbox1" type="checkbox"  name ="nr_ids" id="checkbox_id" value ="11?4">Name11,4</label> <br>

Then I read in this information using a python cgi:

NRs = form.getvalue("nr_ids")
NRids = []
for l in NRs:
    ls = l.split("?")
    NRids.append(ls)

NRs will be ['1?16', '11?4'] if you select both of them. If you select just one, it will be '2?14'

What I wan is a list of lists, where each pair of numbers are subrows: [['1','16'],['11','4']]. This works perfectly well if I select two or more checkboxes. However, I select just 1, the program crashes. NRids becomes [['1'], [','],['1'],['6']]. When I try to take the type of the NRs, nothing prints. I don't know how to automatically check to see if a string or a list has been passed in when they type function doesn't seem to be printing anything.

How could I check to see if only one checkbox has been selected so I don't treat NRs like a list if it is not? Or does anyone have any other suggestions for how I can fix this?

beth
  • 98
  • 3
  • 10
  • Possible duplicate of [What's the canonical way to check for type in python?](http://stackoverflow.com/questions/152580/whats-the-canonical-way-to-check-for-type-in-python) – alexis May 02 '16 at 17:00

2 Answers2

3
if isinstance(a_variable,basestring):
   #its a string of sorts
elif isinstance(a_variable,(list,tuple)):
   #its a list or table

I guess?

timgeb
  • 76,762
  • 20
  • 123
  • 145
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
0

If the processing code is not completely trivial, a nice idiom is to check the type early and convert the simpler case to the more general case; in this case, if the value is not a list, convert it to a one-element list. The rest of the code can then rely on getting a list, sparing you the need to Repeat Yourself:

if not isinstance(NRs, list):
    NRs = [ NRs ]

# Now it's a list for sure...
for l in NRs:
    ...
alexis
  • 48,685
  • 16
  • 101
  • 161