2013-08-02 62 views
0

置字符串我要輸出像列表:的Python:內部列表

operation1 = [ 
    'command\s+[0-9]+', 
] 

當模式[0-9]+要動態填充。

所以我寫了:

reg = { 
    'NUMBER' : '^[0-9]+$', 
    } 

operation1 = [ 
    'command\s+'+str(reg[NUMBER]), 
] 
print operation1 

但我得到一個錯誤:

Message File Name Line Position  
Traceback    
    <module> <module1> 6  
NameError: name 'NUMBER' is not defined    

幫助需要!提前致謝。

回答

1

它應該是reg['NUMBER'],我猜。 'NUMBER'不是變量

0

NUMBER應該是一個字符串:

reg['NUMBER'] 
0

你需要加上引號鍵(Perl的允許不加引號,但不是蟒蛇):

operation1 = [ 
    'command\s+'+str(reg['NUMBER']), 
] 

你也不需要調用str

operation1 = [ 
    'command\s+'+reg['NUMBER'], 
] 

你甚至可以做到這一點(雖然與原始問題無關):

operation1 = [ 
    'command\s+{}'.format(reg['NUMBER']), 
] 
0

您正在使用未定義的變量NUMBER。我想你想要使用的是字符串'NUMBER',像這樣:

>>> operation1 = ['command\s+[0-9]+',] 
>>> reg = {'NUMBER' : '^[0-9]+$'} 
>>> operation1 = [x + reg['NUMBER'] for x in operation1] 
>>> operation1 
['command\\s+[0-9]+^[0-9]+$']