在Python 2.7中删除print中的括号和引号

时间:2014-11-25 11:01:34

标签: python-2.7 readfile text-parsing

我正在尝试使用Python 2.7从print语句中删除括号我尝试了各种论坛的建议,但它没有像预期的那样工作,最后想到自己在这里问。

代码:

    with open('buttonpress_and_commandstarted','r') as buttonpress_commandstarted:
        for line in buttonpress_commandstarted:
            button_press_command_time = ''
            if os.path.getsize('buttonpress_and_commandstarted') > 0:               
                button_press_command_time = line.split()[2]
            else:
                print "   > Cannot get time stamp as the file is empty"
            button_press = re.findall(r"\:12\:(.*?)\.",line)
            command_executed = re.findall(r"\:4\:(.*?) started\.",line)
            with open('timestamp_buttons_and_commands', 'w') as timestamp_buttons_and_commands:
                timestamp_buttons_and_commands.write(str(button_press_command_time) + str(button_press) + str(command_executed))

            with open("timestamp_buttons_and_commands", "r+") as timestamp_buttons_and_commands:
                contents = timestamp_buttons_and_commands.readlines()
                from string import join 
                result = ''.join(contents)
            print result

我不确定我在做什么错。我得到以下输出

00:22:12['Button 9 pressed'][]
00:22:13['Button 9 pressed'][]
00:22:14['Button 9 pressed'][]
00:22:15['Button 9 pressed'][]
00:22:15[]['Command MediaCodec (2)']
00:22:17['Button 9 pressed'][]
00:22:19['Button 9 pressed'][]
00:22:19[]['Command SetSensorFormat (3)']
00:22:22[]['CDC']
00:22:22[]['Command Hello']
00:22:22[]['Command Hello']
00:22:22[]['Command Hello']
00:22:22[]['Command Hello']
00:22:22[]['Command Hello']
00:22:25['Button 10 pressed'][]

但我不想要括号和引号

1 个答案:

答案 0 :(得分:1)

re.findall返回一个列表。当您执行str(someList)时,它将打印括号和逗号:

>>> l = ["a", "b", "c"]
>>> print str(l)
['a', 'b', 'c']

如果您想在没有[,的情况下进行打印,请使用join

>>> print ' '.join(l)
a b c

如果您想在没有[的情况下进行打印,但需要,打印:

>>> print ', '.join(l)
a, b, c

如果您想保留',可以使用repr并列出理解:

>>> print ', '.join(repr(i) for i in l)
'a', 'b', 'c'

编辑后,您的列表中似乎只有1个元素。所以你只能打印第一个元素:

>>> l = ['a']
>>> print l
['a']
>>> print l[0]
a