-4

When I try to split this string:

str1 = ("S8 10 -945 1689 -950 230 -25 1 1e-13")
print(str1[0,1].split(' '))

I get this error print(str1[0,1].split(' ')) TypeError: string indices must be integers

How would I split this the first two indexes of this string in python?

Dabes561
  • 11
  • 2

1 Answers1

0

.split() the string first, and then slice the list to retrieve the first two values.

str = "S8 10 -945 1689 -950 230 -25 1 1e-13"
print str.split(' ')[:2]  # ['S8', '10']
Community
  • 1
  • 1
Sam
  • 20,096
  • 2
  • 45
  • 71
  • And to avoid unnecessary work, pass the `maxsplit` argument to split so it doesn't split beyond the point you care about: `print str1.split(' ', 2)[:2]` does the same thing, while avoiding excess work. – ShadowRanger Sep 14 '15 at 22:31
  • How would I split the S8 of the first index? – Dabes561 Sep 15 '15 at 00:13
  • @Sam: Nope, second argument is 2, not 3. It's the maximum number of splits, not the number of components produced (which is `maxsplits + 1`, assuming there are at least `maxsplits` split points). If you only want two components, you only need two splits, one for each component. Python differs from some other languages here. – ShadowRanger Sep 15 '15 at 10:33
  • How do you ***want*** to split the `S8` of the first index? – Sam Sep 15 '15 at 13:33