Using the for loop and the in operator, it is now possible to print out all the characters in a string.
In this program, we used a for loop to print out all the characters in a string. We assigned repeats of each character in my_string as alphabet. So at first, alphabet is going to be 'g' and when it loops again, alphabet becomes 'r', and then 'e', and then, at last, alphabet would be '!'. When there are no more characters in the string, the loop stops.
We can also add a condition in the loop:
In the string, every character in greater than 'a' except the 'a'. Hence, in our output, 'a' is not printed, but the rest are.
Let's assume there is a huge cake and when we cut each part out of it, we call it a slice; the same can happen with the strings. Slices in python are particular cuts. To make a slice in Python, we will need to use the brackets operator and the colon(:), as such:
string[x:y] --> spliced
We learned about the indices: X and Y are nothing but the indices. X is from which index we want to start the splice, and Y is the end index of the splice. Make sure to remember that Y will not be counted in the splice, but X will be.
In the first example, [1::2], we start the stepping from index 1 and jump 2 indices each time.
[0::2] is the same as [::2]. It doesn't matter whether or not we mention the 0th index. This takes the whole string and jumps it by 2 indices. We could say that this prints out all the even indices, and [1::2] prints out all the odd indices.
[::-1] prints the reverse of a string.
The syntax we were using was [start:stop:step]. We were just mentioning the start and the step, and not mentioning the stop will take the whole string into account.
In Python, we can get an index for any character in a string by using the str.index() function and mentioning the character inside the parentheses, but beware: if the same character repeats twice, Python only prints the index of the first appearance of that character.