Python

Indexing and Slicing in Strings in Python

AKA.DM 2024. 10. 2. 07:29
반응형

In Python, the process of accessing values, characters,  etc. in a data type is called indexing.

Square brackets are used while indexing.

And the index number of the value we want to reach is written in square brackets.

 

For example, we want to reach teh first character of the value in the variable car below.

Since insdex number starts from zero in Python, we wrote zero in square brackets.

 

The process of reaching values, characters, etc. in a data type in Python is called sclicing.

Slicing is done using square brackets just like indexing.

 

We can enter three values inside square just like indexing.

These are Start for the start value, Stop for the end value and step values to determine the number of steps.

 

A colon is placed between these three values.

The stop value we worte in paraentheses is not included in the index. It will return characters up to the stop value

[Start : Stop : Step]

 

For example, we wanted it to return the values from the 1st index to the 5th index from the car variable below.

We did not write it in square brackets as the number of steps is one by default. 

 

Let's work by determining the number of steps.

For example, below, we wanted to get the values starting from the 1st index to the 5th index in the variable car by going in 3 steps.

The character in the 1st index is the letter "e", so Python ouput it. The it took thres steps and got the letter "a".

Then it ended slicing because we said up to the 5th index.

 

If we do not write a stop value, Python will slice up to the last value in the variable after the value we set as the start.

For example, since the start parameter is three, below, it started from the 3rd index and output all the values until the end.

 

Python proceeds up to the stop value and slices if we do not write a start value.

For example, becuase the stop paramete is three, below, it ouputs the values up to the 3rd index.

 

 

반응형