I am trying to split a fist and middle name. the number of names is not always two:
Name |
WILLIAM LEWIS |
SAMMY L |
ROCKY |
ROCKY |
ORA SETH |
How can I split these into two columns?
You could use enumerate
>>> names = [
... "WILLIAM LEWIS",
... "SAMMY L",
... "ROCKY",
... "ORA SETH"
... ]
>>>
>>> for name in names:
... f_m = [""]*2
... for i,n in enumerate(name.split()):
... f_m[i] += n
... print("First name is '{}' and middle name is '{}'".format(*f_m))
...
First name is 'WILLIAM' and middle name is 'LEWIS'
First name is 'SAMMY' and middle name is 'L'
First name is 'ROCKY' and middle name is ''
First name is 'ORA' and middle name is 'SETH'
>>>
or zip_longest
>>> from itertools import zip_longest
>>>
>>> names = [
... "WILLIAM LEWIS",
... "SAMMY L",
... "ROCKY",
... "ORA SETH"
... ]
>>>
>>> for name in names:
... first, middle = [f+m for f,m in zip_longest([""]*2, name.split(), fillvalue="")]
... print("First name is '{}' and middle name is '{}'".format(first,middle))
...
First name is 'WILLIAM' and middle name is 'LEWIS'
First name is 'SAMMY' and middle name is 'L'
First name is 'ROCKY' and middle name is ''
First name is 'ORA' and middle name is 'SETH'
>>>