0
MyString = "150 250 400 480"
MyString = MyString.split(" ",2)
print(MyString)    

When I run it on spyder, the program spits out 3 elements:

['150', '250', '400 480']

It should just return first 2 elements (as specified):

['150', '250']

Why is this happening?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • 8
    Nothing is wrong, `['150', '250', '400 480']` is correct,it splitted two times, between 150 and 250, and between 250 and the "400 800". the "400 800" are not splitted. if you want the first two elements use `splitted[:2]` – Jonathan1609 Jun 30 '21 at 21:18
  • Thanks for your answer Jonathan, but I did it like you said and it returned just 15. – Guilherme Mendonça Jun 30 '21 at 21:34
  • you have to combine both: MyString.split(" ",2)[:2] – zanga Jun 30 '21 at 21:36
  • 2
    The second parameter of the method defines how many splits are done, not how many elements are returned: [`string.split(separator, maxsplit)`](https://www.w3schools.com/python/ref_string_split.asp) – hc_dev Jun 30 '21 at 21:37
  • 2
    @GuilhermeMendonça the `[:2]` was meant to be used with `MyString.split(" ",2)`,not with `MyString`. [as `MyString.split(" ",2)[:2]`] – Jonathan1609 Jun 30 '21 at 21:38
  • 1
    It worked! Thank you so much for your answers! – Guilherme Mendonça Jun 30 '21 at 21:44

0 Answers0