Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i split a python list element without creating a sublist

Tags:

python

I am trying to extract some info from a line of text from a log file, the line has a few odd separators which I can get around with split/replace/join etc.

The issue comes when I try to then split the second time element at the '-' and add it back to the list, I end up with a sublist - which is not what I want.

line='2016-05-06T12:00:00.128189+01:00 mac-68c90b45b51e debug: 03959725-10:59:57.250[51222]*** NEW STATUS [3896374] : id=15 object=1 row=00408280 speed=0 crit=2 cell=130 intracell=512'

line1=(" ".join(line.split()).replace('[', '.').replace(']', ' ').strip().split())

Results in;

['2016-05-06T12:00:00.128189+01:00', 'mac-68c90b45b51e', 'debug:', 03959725-10:59:57.250.51222', '***', 'NEW', 'STATUS', '.3896374', ':', 'id=15', 'object=1', 'row=00408280', 'speed=0', 'crit=2', 'cell=130', 'intracell=512']

When I then try to split '03959725-10:59:57.250.51222' with

line1[3]=line1[3].replace('-', ' ').split()

I end up with;

['2016-05-06T12:00:00.128189+01:00', 'mac-68c90b45b51e', 'debug:', ['03959725', '10:59:57.250.51222'], '***', 'NEW', 'STATUS', '.3896374', ':', 'id=15', 'object=1', 'row=00408280', 'speed=0', 'crit=2', 'cell=130', 'intracell=512']

What I would like is;

    ['2016-05-06T12:00:00.128189+01:00', 'mac-68c90b45b51e', 'debug:', '03959725', '10:59:57.250.51222', '***', 'NEW', 'STATUS', '.3896374', ':', 'id=15', 'object=1', 'row=00408280', 'speed=0', 'crit=2', 'cell=130', 'intracell=512']

Any ideas on how to tidy up the way I do it?

like image 627
Edward Hickinbotham Avatar asked Aug 15 '26 05:08

Edward Hickinbotham


2 Answers

You can use slice assignment:

line1[3:4]=line1[3].replace('-', ' ').split()

It will replace the slice with given sequence:

>>> l = [1, 2, 3, 4, 5]
>>> l[3:4] = ['new', 'items']
>>> l
[1, 2, 3, 'new', 'items', 5]
like image 174
niemmi Avatar answered Aug 17 '26 19:08

niemmi


If you have Python3.5, there's also this fun way:

>>> a = [0, 1, 2, 'hello world whats up?', 4, 5]
>>> n = 3
>>> [*a[:n], *a[n].split(), *a[n+1:]]
[0, 1, 2, 'hello', 'world', 'whats', 'up?', 4, 5]
like image 34
timgeb Avatar answered Aug 17 '26 20:08

timgeb