-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
  • 1,048,767
  • 296
  • 4,058
  • 3,343
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
  • 244,495
  • 58
  • 464
  • 504
3

Subtract 1 from indices for 0 indexed

>>> text = "I am a boy!"
>>> text[2:4]
'am'
jamylak
  • 128,818
  • 30
  • 231
  • 230
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
  • 33,167
  • 7
  • 69
  • 71