0

I was trying to split the element inside the list based on certain length, here is the list ['Mar 18 Mar 17 Mar 16 Mar 15 Mar 14']. Could any one help me to retrieve the values from the list in the following format:

['Mar 18','Mar 17','Mar 16','Mar 15','Mar 14']

Sumit S Chawla
  • 3,180
  • 1
  • 14
  • 33
Jagan S
  • 13
  • 2
  • 5
    have you tried some thing? – Shanteshwar Inde Dec 28 '18 at 06:50
  • i have gone through the link and this doesnt solve my problem. The link explains about splitting a string in to two and set as constant, where as in my question the number of values may vary every time. schwobaseggl answer helped me to solve the issue. Thanks – Jagan S Dec 28 '18 at 07:44

4 Answers4

1

A regular expression based approach that would handle cases like Apr 1 or Dec 31 as well as multiple elements in the initial list:

import re

lst = ['Mar 18 Mar 17 Mar 16 Mar 15 Mar 14']

[x for y in lst for x in re.findall(r'[A-Z][a-z]+ \d{1,2}', y)]
# ['Mar 18', 'Mar 17', 'Mar 16', 'Mar 15', 'Mar 14']
user2390182
  • 72,016
  • 6
  • 67
  • 89
0
list = ['Mar 18 Mar 17 Mar 16 Mar 15 Mar 14']

span = 2
s = list[0].split(" ")
s = [" ".join(words[i:i+span]) for i in range(0, len(s), span)]
print(s)

For me, this prints

['Mar 18','Mar 17','Mar 16','Mar 15','Mar 14']

Taken from this answer.

rLevv
  • 498
  • 3
  • 12
0

Try this code !

You can do it by the concept of regular expression (just by import re library in python)

import re

lst = ['Mar 18 Mar 17 Mar 16 Mar 15 Mar 14 Mar 2']

obj = re.findall(r'[A-Z][a-z]+[ ](?:\d{2}|\d{1})', lst[0])

print(obj)

Output :

['Mar 18', 'Mar 17', 'Mar 16', 'Mar 15', 'Mar 14', 'Mar 2']

Usman
  • 1,983
  • 15
  • 28
0

You can also try this one

>>> list = ['Mar 18 Mar 17 Mar 16 Mar 15 Mar 14']
>>> result = list[0].split(" ")
>>> [i+' '+j for i,j in zip(result[::2], result[1::2])]

Output

['Mar 18', 'Mar 17', 'Mar 16', 'Mar 15', 'Mar 14']
Anoop Kumar
  • 845
  • 1
  • 8
  • 19