问题
I am trying to remove the brackets from the print statement using Python 2.7 I tried suggestions from various forums but it didn't work as expected finally thought of asking out here myself.
Code:
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
I am not sure what mistake I am doing.I get the following output
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'][]
But I don't want the brackets and quotes
回答1:
re.findall
returns a list. When you do str(someList)
, it will print the brackets and commas:
>>> l = ["a", "b", "c"]
>>> print str(l)
['a', 'b', 'c']
If you want to print without [
and ,
, use join
:
>>> print ' '.join(l)
a b c
If you want to print without [
but with ,
:
>>> print ', '.join(l)
a, b, c
And if you want to keep the '
, you could use repr
and list comprehension:
>>> print ', '.join(repr(i) for i in l)
'a', 'b', 'c'
After your edit, it seems that there is only 1 element in your lists. So you can only print the first element:
>>> l = ['a']
>>> print l
['a']
>>> print l[0]
a
来源:https://stackoverflow.com/questions/27124891/removing-brackets-and-quotes-from-print-in-python-2-7