简体   繁体   中英

Determining whether an iterable is a string or list in python

I've made an html page that has several checkboxes. Each value of a checkbox are two numbers separated by a question mark sign, ie "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?

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

I guess?

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:
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM