gatorback gatorback - 1 year ago 89
Python Question

Cleaving and inserting a token


myString = "Athletes like baseball and basketball"
tokens = myString.split()
['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 Source

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:]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download