0

The answer to a question on multiple-value elements in a config file (which exactly fits my needs) suggests to "unpack the string from the config". I read the doc for unpacking arguments lists suggested in several places but I fail to understand how this relates to my problem.

I am sure this must be obvious: having a string str = "123,456", how can I transform it into the list [123,456] (the number of elements separated by a comma in the string may vary)

Thank you.

Community
  • 1
  • 1
WoJ
  • 27,165
  • 48
  • 180
  • 345
  • Thank you for the responses. I learned something with the map() function. Also "str" is indeed a bad name for a function, I usually use the thisString version (but Murphy's law dictates that I used "str" when posting worldwide :)) – WoJ Jun 25 '12 at 19:56

4 Answers4

5
[int(x) for x in str.split(",")]

You're basically applying the function int to each element produced by split of your string.

The result of simply str.split(',') would be ["123","456"].

As Daniel Roseman pointed out, you should be careful not to use variable or method names that inadvertently overshadow built in methods, like, for instance, str.

pcalcao
  • 15,789
  • 1
  • 44
  • 64
4

Do you want a list of strings or a list of ints?

If you just want a list of strings, it's very simple:

my_list = my_string.split(',')

If you want to convert these to ints, you need:

my_list = map(int, my_string.split(','))

(Also, don't use str as a variable name as it shadows the built-in str() function.)

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Out of curiosity, is there any noticeable difference in terms of performance between using `map` or simply the syntax I presented? – pcalcao Jun 25 '12 at 16:02
  • Not really. To be honest, I usually use the list comprehension myself, but typed in `map` this time because it's quicker to type :-) – Daniel Roseman Jun 25 '12 at 16:03
0

The easiest way would be to use split().

unpacked = str.split(',')
betabandido
  • 18,946
  • 11
  • 62
  • 76
TaoJoannes
  • 594
  • 5
  • 14
0

Although I agree with the other answers, you should also handle exceptions in the case of invalid string representation of a supposed number. Take, for example, the following snippet:

number_string = "123,456,x21"
delimiter = ","
number_list = []
for item in number_string.split(delimiter):
    try:
        my_num = int(item)
        number_list.append(item)
    except ValueError, e:
        # you can choose to just pass or handle the error like so
        print "Skipping %s: %s" % (item, e.message)

Just a thought. Good luck!

Paul Rigor
  • 986
  • 1
  • 12
  • 23