【问题标题】:Removing brackets and quotes from print in Python 2.7在 Python 2.7 中从 print 中删除括号和引号
【发布时间】:2014-11-25 11:01:33
【问题描述】:

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

代码:

    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'][]

但我不想要括号和引号

【问题讨论】:

  • 一般提示:不要在代码中间导入模块
  • 当然谢谢@TimCastelijns
  • 不清楚您的问题是什么 - 您能否将代码缩减为 minimal example 并提供输入以及预期和实际输出?
  • 另外,我认为您对join 的使用是错误的。您从string 导入join 并且从不使用它,而是使用内置的,这是相同的。因此,导入是没有意义的。
  • 好的,谢谢@go2 那我就删了

标签: python-2.7 readfile text-parsing


【解决方案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

【讨论】:

  • 添加这些行button_press = ''.join(button_press) command_executed = ''.join(command_executed) timestamp_buttons_and_commands.write(str(button_press_command_time) + " : " + str(button_press) + str(command_executed)) 成功了!非常感谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-24
  • 2022-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-29
相关资源
最近更新 更多