Python

Complex Indexing and Slicing Operations in Python

AKA.DM 2024. 10. 10. 07:52
반응형

Strings have negative indexing as well as positive indexing.

Positive indexing starts from the first character of the string value and the first index number is zero. We know this.

In negative indexing, it starts from the last value and progresses to the beginning.

Index numbers starts from -1 in negative indexing.

We can index according to these index numbers : 

 

Indexing using negative index nunbers is the same as the logic of positive indexing.

Indexing is done using square brackets.

For example, we called the "-3" index to reach the letter "a" of the value in the car variable below.

 

Slicing using negative index numbers is the same as positive slicing logic.

Slicing is done using square brackets.

Likewise, start, stop, and end parameters are used.

 

[Start : Stop : Step]

 

For example, below, we wanted to slice the "rra" seciton from the "Ferrari" value.

We set it as the start paramteres since the letter "R" is in the -5th idex.

Then, since we wanted the letter "a", we set the stop paramter up to the letter "r". So we set it to -2. If ytou remember, stop value was not included in slicing. It would be up to the stop value.

We left the stop parameter as default because the number of steps is one. 

 

Addtion 

Values[::-1] utilizes slicing with a step of -1, which essentially reserves the strings.

반응형