The Python string data type is a sequence made up of one or further individual characters that could correspond to letters, figures, whitespace characters, or symbols. As the string is a sequence, it can be penetrated in the same ways that other sequence-grounded data types are, through indexing and slicing.
Indexing means pertaining to an element of an iterable by its position within the iterable. Each of a string’s characters corresponds to an indicator number and each character can be penetrated using their indicator number.
We can pierce characters in a String in Two ways
Penetrating Characters by Positive Indicator Number
Penetrating Characters by Negative Indicator Number
1. Penetrating Characters by Positive Indicator Number
In this type of Indexing, we pass a Positive indicator (which we want to pierce) in square classes. The indicator number starts from indicator number 0 (which denotes the first character of a string).
- String indexing allows us to access individual characters in a string.
- We can do this by using square brackets and the location, or index, of the character you want to access.
- It’s important to remember that Python starts indexes at 0. So to access the first character in a string, you would use the index.
- If we try to access an index that’s larger than the length of your string, you’ll get an Index Error.
- This is because you’re trying to access something that doesn’t exist.
- We can also access indexes from the end of the string going towards the start of the string by using negative values.
- The index[-1] would access the last character of the string, and the index[-2] would access the second-to-last character.
- We can also access a portion of a string, called a slice or a sub-string. This allows you to access multiple characters of a string.
- We can do this by creating a range, using a colon as a separator between the start and end of the range, like[2:5].
- This range is similar to the range () function. It includes the first number but goes to one less than the last number.
- We can also easily reference the start or end of the string by leaving one value blank. For example[:5] would give us all characters from the start to the fourth character in the string.
- We can also use [5:] to get the characters from the fourth character to the end of the string.