There is always couple of minutes to spare and use them for thinking. Majority of assignments are solvable with 'pure' thinking. Some potentially useful tidbits:
- separate
what from
how - define what you want to do first and only after that start coding.
- use spoken language for defining what you want to do
- decompose tasks into subtasks
What for current assignment:
- I want get names and birthdays from rows
- I want to print out name and birthday in specific formatting
What: Get names and birthdays
Using just common sense analyse rows. The pattern which should emerge is that row must be split into two, starting from first decimal encountered (as discussed earlier, there can be more than two names therefore whitespace splitting can be error prone). This observation has nothing to do with coding, it's about finding general pattern.
What: Split line onto two parts on first decimal
How? We need index of the first decimal number and then slice string on this index.
Getting index is easy enough:
>>> s = 'a1b2c3'
>>> s.index('1')
1
>>> s.find('2')
3
However, we must find occurrence any decimal, not specific one. How? Quite logical step will be 'iterate over string character by character and when decimal is encountered return it's index':
>>> [s.index(char) for char in s if char.isdecimal()] # alternatively char in '0123456789'
[1, 3, 5]
We have all indices but actually need only first. We could 'create list of decimal indexes and get first index'
>>> [s.index(char) for char in s if char.isdecimal()][0]
1
or we could 'create generator of decimal indices and take first':
>>> index = next(s.index(char) for char in s if char.isdecimal())
>>> index
1
Now we know the index where to split. Let's test:
>>> n = 'Guido van Rossum 31 January 1956'
>>> index = next(n.index(char) for char in n if char.isdecimal())
>>> name, birthday = n[:index], n[index:]
>>> name
'Guido van Rossum ' # observe space at end, to get rid of it one can use n[:index].strip() on row #3
>>> birthday
'31 January 1956'
What: print out in specific formatting
When we have name and birthday it's easy to construct string in required formatting:
>>> s = 'Guido van Rossum 31 January 1956', 'Orville Wright 21 July 1988'
>>> for row in s:
... index = next(row.index(char) for char in row if char.isdecimal())
... name, birthday = row[:index], row[index:]
... print(f'Name:\n{name}\n\nBirthday:\n{birthday}\n')
...
Name:
Guido van Rossum
Birthday:
31 January 1956
Name:
Orville Wright
Birthday:
21 July 1988
# observe newline at end