0

I have a list below:

list = [' ab: 1', ' cd: 0', ' ef: 2 gh: 3', ' ik: 4']

From above list, I need something like below:

newlist = [' ab: 1', ' cd: 0', ' ef: 2', ' gh: 3', ' ik: 4']

So "list" contains 4 elements and then I need "newlist" to contain 5 elements.

Is there any way split() can be used here?

2
  • Are these leading spaces meaningful and required? Commented May 12, 2022 at 7:14
  • Even for quick example, try to avoid naming your variable with python built in like list ! Commented May 12, 2022 at 7:15

3 Answers 3

2

I would approach this by using re.findall in the following way:

import re

li = [' ab: 1', ' cd: 0', ' ef: 2 gh: 3', ' ik: 4']
newlist = []
for ele in li:
    match = re.findall(r"\w+\s?:\s?\d+", ele)
    newlist += [m for m in match]

print(newlist)

Output:

['ab: 1', 'cd: 0', 'ef: 2', 'gh: 3', 'ik: 4']
Sign up to request clarification or add additional context in comments.

8 Comments

re.findall seems great to use. Can I use it in such a way to not make any modification to 1st element of my original list.
@Ab20, you mean you want to keep leading spaces?
For eg: if I have a list like this, list = ['first.t: ab: 1', ' cd: 0', ' ef: 2 gh: 3', ' ik: 4']
and my new list should be like this: newlist = ['first.t: ab: 1', ' cd: 0', ' ef: 2', ' gh: 3', ' ik: 4']
I mean my 1st element in list, i.e. list[0] should not get modified
|
0

Checking method for the best.

list_name = [' ab: 1', ' cd: 0', ' ef: 2 gh: 3', ' ik: 4']
newlist = []
for value in list_name:
    if len(value) > 6:
        newlist.append(value[0:6])
        newlist.append(value[6:])
    else:
        newlist.append(value)
print(newlist)

as you can see, python have a great syntax called slicing (value[0:6])

if you learned about range(start,stop,step) you can use this as well list_name[start:stop:step]

the empty value will automaticaly set into the default [0,-1,1]

have fun :)

Comments

0

Try this:

newlist = []

for i in a:
    if len(i.split()) != 1:
        for key, val in zip(i.split()[::2], i.split()[1::2]):
            newlist.append(key + val)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.