-1

I built this simple little function to split a 6 character string into two segments, but why isn't it returning two 3-letter results? Ie, I would have thought:

FXPair[0:2] => 0, 1, 2 in terms of indexing?

def ISOCodes(FXPair):
    ccy1 = FXPair[0:2]
    ccy2 = FXPair[3:5]
    return [ccy1, ccy2]

ISOCodes('USDCAD')

['US', 'CA']

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
keynesiancross
  • 3,441
  • 15
  • 47
  • 87
  • 1
    As to why slices are half open, read https://stackoverflow.com/questions/11364533/why-are-slice-and-range-upper-bound-exclusive – Ilja Everilä May 27 '17 at 20:50

2 Answers2

6

Indexing is exactly the same for strings and lists, and in fact any indexable object.

However, you've misunderstood how slicing works. Slices are half-open; in other words, the lower bound is included, but the upper bound is not. Slicing anything [0:2] gets you just indexes 0 and 1, and similarly [3:5] gets you just 3 and 4.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
2

you can use [:3] and [3:] as the following:

def ISOCodes(FXPair):
    ccy1 = FXPair[:3]
    ccy2 = FXPair[3:]
    return [ccy1, ccy2]

output:

['USD', 'CAD']
Mohd
  • 5,523
  • 7
  • 19
  • 30