Python, string (consisting of variable and strings, concatenated) used as new variable name?

I've been searching on this but am coming up a little short on exactly how to do specifically what i am trying to do.. I want to concatentate a string (I guess it would be a string in this case as it has a variable and string) such as below, where I need to use a variable consisting of a string to call a listname that has an index (from another variable).. I simplified my code below to just show the relevant parts its part of a macro that is replacing values:

toreplacetype = 'type'
toreplace_indx = 5
replacement_string = 'list'+toreplacetype[toreplace_indx]

so... I am trying to make the string on the last line equal to the actual variable name:

replacement_string = listtype[5]

Any advice on how to do this is appreciated

EDIT:

To explain further, this is for a macro that is sort of a template system where I am indicating things in a python script that I want to replace with specific values so I am using regex to do this. So, when I match something, I want to be able to replace it from a specific value within a list, but, for example, in the template I have {{type}}, so I extract this, but then I need to manipulate it as above so that I can use the extracted value "type" to call a specific value from within a list (such as from a list called "listtype") (there is more than 1 list so I need to find the one called "listtype" so I just want to concatenate as above to get this, based on the value I extracted using regex

1
задан Rick 25 August 2010 в 02:23
поделиться

3 ответа

Это не рекомендуется. Вместо этого используйте dict.

vars['list%s' % toreplacetype][5] = ...
1
ответ дан 2 September 2019 в 21:53
поделиться

Грм...

globals()['list%s'% toreplacetype][toreplace_indx]
1
ответ дан 2 September 2019 в 21:53
поделиться
replacement_string = 'list'+toreplacetype+'['+str(toreplace_indx)+']'

при печати даст listtype[5].

Вам нужно разбить его на 5 частей: 1 строковая переменная, 3 строки и целочисленное преобразование в строку.

Я думаю, это то, о чем вы спрашиваете?

0
ответ дан 2 September 2019 в 21:53
поделиться
Другие вопросы по тегам:

Похожие вопросы: