Skip to content
Advertisement

How to go back a character in a string in Python

What I’m trying to figure out is how to go back a position in a string. Say I have a word and I’m checking every letter, but once I get to a “Y” I need to check if the character before was a vowel or not. (I’m a beginner in this language so I’m trying to practice some stuff I did in C which is the language I’m studying at college).

I’m using a For loop to check the letters in the word but I don’t know if there’s any way to go back in the index, I know in C for example strings are treated like arrays, so I would have a For loop and once I get to a “Y”, that would be my word[i] (i being the index of the position I’m currently at) so what I would normally do is check if word[i-1] in "AEIOUaeiou" (i-1 being the position before the one I’m currently at). Now I don’t know how that can be done in python and it would be awesome if someone could give me a hand :(

Advertisement

Answer

There’s a good answer here already but I wanted to point out a more “C-like” way to iterate strings (or anything else).

Some people may considered it un-Pythonic but in my opinion it’s often a good approach when writing certain algorithms:

word = "today"
len_word = len(word)

vowels = "aeiou"

i = 0
while i < len_word:
    if word[i] == "y":
        if word[i-1].lower() in vowels:
            print(word[i-1])

    i += 1

This approach gives you more flexibility, for example, you can do more complex things like “jumping” back and forth with the index, however, you also need to be more careful not to set the index to something that is out of range of the iterable.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement