Converting a list of strings into a list of integers?
Roy Smith
roy at panix.com
Sun Jul 22 11:39:30 EDT 2012
In article <3rCdnUCiWpP1gZHNnZ2dnUVZ7vQAAAAA at giganews.com>,
Tony the Tiger <tony at tiger.invalid> wrote:
> Hi,
> Is there such a thing in the language, or do I have to invent it myself?
>
> I came up with the following:
>
> # options.modus_list contains, e.g., "[2,3,4]"
> # (a string from the command line)
> # MODUS_LIST contains, e.g., [2,4,8,16]
> # (i.e., a list of integers)
>
> if options.modus_list:
> intTmp = []
> modTmp = options.modus_list[1:-1]
> for itm in modTmp:
> intTmp.append(int(itm))
> MODUS_LIST = intTmp
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]
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.
More information about the Python-list
mailing list