Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shift vowels in input string with Python

Tags:

python

string

I am trying to write a function that would let me shift the individual letters in a string. The string comes from the input.

I'm looking at vowels so "a, e, i, o, u"

I would like the individual letter to be shifted one to the right. i.e the world "me" would become "mi" as i is the next letter after e.

this is what I have so far:

import random
vowels = ("a", "e", "i", "o", "u")

message = input("Enter a string")

new_message = ""

for letter in message:
    if letter not in vowels:
        new_message += letter
    else:
        new_message += random.choice(vowels)
        
print(new_message)

However, this randomizes the changing of the individual vowels, what would be the best way to make it shift to the next letter?

like image 400
Nairda123 Avatar asked Dec 30 '22 23:12

Nairda123


1 Answers

If you want to translate the whole string, then I would look at str.translate.

Here is a simple example working with your vowels:

>>> v = "aeiou"
>>> vDict = {v[i]: v[(i+1)%len(v)] for i in range(len(v))}
>>> vDict
{'a': 'e', 'e': 'i', 'i': 'o', 'o': 'u', 'u': 'a'}
>>> "This is a test-string. hope it works!".translate(str.maketrans(vDict))
'Thos os e tist-strong. hupi ot wurks!'
like image 101
Hampus Larsson Avatar answered Jan 06 '23 01:01

Hampus Larsson