Wednesday, July 18, 2018

python - Splitting on first occurrence

You can also use str.partition:


>>> text = "123mango abcd mango kiwi peach"
>>> text.partition("mango")
('123', 'mango', ' abcd mango kiwi peach')
>>> text.partition("mango")[-1]
' abcd mango kiwi peach'
>>> text.partition("mango")[-1].lstrip() # if whitespace strip-ing is needed
'abcd mango kiwi peach'

The advantage of using str.partition is that it's always gonna return a tuple in the form:


(
, , )

So this makes unpacking the output really flexible as there's always going to be 3 elements in the resulting tuple.

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...