-3

I want to find sub-string using indexes, like:

"I am a boy!" 

and if I have positions 3 and 5, then the sub-string will be "am".

Is there a command or way to do this?

Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187
Luqman
  • 19
  • 5

3 Answers3

4

You can use slicing. As indexes are 0 based in python so you've to use 2 and 4.

>>> strs = "I am a boy!"
>>> strs[2:4]            
'am'

If you're new to slicing : Explain Python's slice notation

Community
  • 1
  • 1
Ashwini Chaudhary
  • 232,417
  • 55
  • 437
  • 487
3

Subtract 1 from indices for 0 indexed

>>> text = "I am a boy!"
>>> text[2:4]
'am'
jamylak
  • 120,885
  • 29
  • 225
  • 225
1

You can use slicing, like follows. You'll have to subtract 1 from your index, since indexing starts from 0 i.e the first character is at index 0.

>>> string = "I am a boy!"
>>> startPosition = 3
>>> endPosition = 5
>>> string[startPosition-1:endPosition-1]
'am'
Sukrit Kalra
  • 30,727
  • 7
  • 64
  • 70