0

I would like to convert a list of string to sequence of variables. For example, i have a list my_list=["var1","var2","var3"]and i want to create a line with var1,var2,var3 = map(str.strip, line.split()) (because my list and my line of variables of course, is variable).

Please can you give me few leads?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Tof
  • 301
  • 5
  • 17
  • Are the variables local or global? – Martijn Pieters Mar 06 '13 at 19:00
  • 9
    While technically achievable, 99% of the time, if you are trying to do something like this, it is because there's a more fundamental design problem with your code. Could you provide an example of what you are trying to accomplish with this functionality? – Silas Ray Mar 06 '13 at 19:07
  • 3
    And: any reason why a mapping or list doesn't fit your needs? – Martijn Pieters Mar 06 '13 at 19:07
  • I parse a text file to get the header which contain a list of files : file1 file2 file3, but the number of files is variable depending of file. So, i think if i get the number of files and i create the same number of variables, it could possibility work. – Tof Mar 06 '13 at 19:43
  • @MartijnPieters local variable – Tof Mar 06 '13 at 19:44
  • @Tof: In python 3: You can't. In python 2: You shouldn't, it'll impact performance of that function as the name lookup optimizations need to be disabled. You can only do it with `exec` in that case. For globals it can work a lot better, but usually you just use a mapping or a list *instead*. – Martijn Pieters Mar 06 '13 at 20:05
  • Creating a new identifier ``var`` from string ``'var'`` (remark the quotes in the latter and their absence in the former) and an assignement of ``'var'`` with an object **var** is possible: it means that a new key-value pair (``'var'``,**var**) is created in a namespace. ``locals()`` and ``globals()`` are dictionaries representing a local and the global namespaces. Hence if you want to create such a new assignement from a string, see this answer of mine that shows how one can do (http://stackoverflow.com/questions/5036700/how-can-you-dynamically-create-variables-in-python-via-to-a-while-loop) – eyquem Mar 06 '13 at 20:40
  • i will check all that!! – Tof Mar 06 '13 at 21:59
  • @Tof: In that case, why not have a list (or a dictionary) instead of a bunch of variables? – David Robinson Mar 06 '13 at 23:24
  • In fact i parse a text file to get the different columns for then use them with this command : `var1, var2, var3 = map(str.strip, line.split())` if there is 3 columns but my text file is variable and it could have 4 columns so i must create 4 variables like that : `var1, var2, var3, var4= map(str.strip, line.split())` – Tof Mar 07 '13 at 07:52

0 Answers0