Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string in python in 2 parts backwards

I am trying to split my string str = 'I HAVE 6' in two parts. The output should be
['I HAVE','6']
There is no info about the length of the words given as input. One way do this is to split it in three and add the first two. Is there any other way?

like image 256
impopularGuy Avatar asked Sep 21 '25 08:09

impopularGuy


1 Answers

You can use rsplit, which splits from the right, with a maxsplit of 1:

s = 'I HAVE 6'
s.rsplit(maxsplit=1)  # or (' ', 1)
['I HAVE', '6']

As an aside, don't use the name str. It masks the built-in class str and will lead to errors down the line.

like image 132
Dimitris Fasarakis Hilliard Avatar answered Sep 22 '25 22:09

Dimitris Fasarakis Hilliard