gatorback gatorback - 1 month ago 6
Python Question

Cleaving and inserting a token

CONTEXT:

myString = "Athletes like baseball and basketball"
tokens = myString.split()
tokens
['Athletes', 'like', 'baseball', 'and', 'basketball']


QUESTION: is there a clever & elegant command that directs the third token string to be cleaved at position 4 into two tokens such that the result is

>>> tokens
['Athletes', 'like', 'base', 'ball', 'and', 'basketball']


The cleaving mechanism should be performed on the basis of the position (i.e. four characters from right)

Bonus for concatenating base + ball and restoring the array back to 5 elements

Answer

I find

tokens = tokens[:2] + [tokens[2][:4], tokens[2][4:]] + tokens[3:]

elegant enough. And the inverse:

tokens = tokens[:2] + [tokens[2] + tokens[3]] + tokens[4:]