i have a python string
word = helloworld
the answer for
word[1:9:2] will be given as "elwr". How this is happening? Thank you!!

- 232,561
- 37
- 312
- 386

- 33
- 1
- 5
4 Answers
You're asking for an explanation of Python's slice notation. See this answer for details. In particular, notice that:
word = 'helloworld'
word[1:9:2]
... Is stating that a new slice should be created, beginning at index 1, up to (and not including) index 9, taking one element every two indexes in the string. In other words, create a new string with the following elements:
0 1 2 3 4 5 6 7 8 9
h e l l o w o r l d
^ ^ ^ ^
... And that's how you obtain 'elwr'
as a result.

- 1
- 1

- 232,561
- 37
- 312
- 386
This means that you are taking a sub-string from position[1] to position[9] and in that you are taking only the 2nd letter. Sub-string would be something like :
elloworld
and since you are taking the character at index 2 from that it would be :
elwr
Also its not an array. Its just a string.

- 5,785
- 5
- 35
- 68
array[begin:end:step]
word[1:9:2]
means you begin at index 1, and up until index 9, take every second letter.

- 735
- 3
- 16
-
There are no arrays in Python. – Burhan Khalid Feb 11 '13 at 04:19
That is array slicing - word[start_pos:end_pos:step]
, where start_pos
and end_pos
are zero-indexed and step
is the value at which the index is incremented on each iteration. The character/element at end_pos
is omitted from the result.
|h|e|l|l|o|w|o|r|l|d|
0 1 2 3 4 5 6 7 8 9 10
^---------------^
start end
Since step = 2
in your example, we would just take every other character from the range above.
>>> word = "helloworld"
>>> word[1]
'e'
>>> word[1:9]
'elloworl'
>>> word[1:9:2]
'elwr'

- 7,870
- 4
- 36
- 52