Converting a list of strings into a list of integers?

Peter Otten __peter__ at
Sun Jul 22 18:30:48 CEST 2012

Tony the Tiger wrote:

> On Sun, 22 Jul 2012 11:39:30 -0400, Roy Smith wrote:
>> To answer the question you asked, to convert a list of strings to a list
>> of ints, you want to do something like:
>>   MODUS_LIST = [int(i) for i in options.modus_list]
> Thanks. I'll look into that. I now remember reading about the technique
> (in Mark Lutz' "Learning Python"), but it seems I'm getting old as I tend
> to forget about it from time to time. ;)
>> But, to answer the question you didn't ask, if you're trying to parse
>> command-line arguments, you really want to use the argparse module. It's
>> a little complicated to learn, but it's well worth the effort.
> Your suggestions about the argparse. Well, it seems it does pretty much
> the same as OptionParser which I use now. Perhaps it has more features
> (that I probably won't need in my 30 line script), I only need to keep
> track of maybe one or two options. Maybe one of these days, when I have
> little else to do, or when the OptionParser stops working, I'll give it a
> try. Thanks. :)

Here's an argparse example:

$ cat
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-m", "--modus", type=int, nargs="*")

print parser.parse_args().modus
$ python 
$ python -m
$ python -m 1
$ python -m 1 2 3
[1, 2, 3]

More information about the Python-list mailing list