Python:在列表中连接字符串

时间:2013-08-02 06:17:27

标签: python list concatenation

我想输出如下列表:

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             

需要帮助!提前谢谢。

4 个答案:

答案 0 :(得分:1)

我想,它应该是reg['NUMBER']。 &#39; NUMBER&#39;不是变量

答案 1 :(得分:0)

NUMBER应为字符串:

reg['NUMBER']

答案 2 :(得分:0)

您需要将密钥放在引号中(Perl不允许添加引号,但不能添加Python):

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

您也不需要拨打str

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

您甚至可以这样做(虽然与原始问题无关):

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

答案 3 :(得分: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]+$']