Summary: In this programming example, we will learn to convert a string or sentence into Pig Latin using Python programming.
What is Pig Latin?
It is said that Pig Latin is not any kind of language but is a language game that children use to speak in code. It is formed by altering the letters in a word.
Here’s how it works:
First, pick an English word. We’ll use dictionary.
Next, move the first consonant or consonant cluster to the end of the word: “ictionary-d”.
Now add “ay” to the end of the word: “ictionary-day”.
That’s all there is to it; you’ve formed a word in Pig Latin.
I recommend you to read more about Pig Latin on the wiki.
Now we have some idea what exactly is Pig Latin, so let’s try converting a whole sentence into its Pig Latin form.
sentence = input('Enter a Sentence: ').lower() words = sentence.split() for i, word in enumerate(words): ''' if first letter is a vowel ''' if word in 'aeiou': words[i] = words[i]+ "ay" else: ''' else get vowel position and postfix all the consonants present before that vowel to the end of the word along with "ay" ''' has_vowel = False for j, letter in enumerate(word): if letter in 'aeiou': words[i] = word[j:] + word[:j] + "ay" has_vowel = True break #if the word doesn't have any vowel then simply postfix "ay" if(has_vowel == False): words[i] = words[i]+ "ay" pig_latin = ' '.join(words) print("Pig Latin: ",pig_latin)
Enter a Sentence: Pencil Programmer
Pig Latin: encilpay ogrammerpray
- Input a sentence using the
- Split it into a list of words using
- Loop through the words and check if any of them begins with vowels.
- If yes, then concatenate “ay” and update the word in the word’s list.
- Else check if there is any vowel present in between the word.
- If yes then get the first vowel index position and postfix all the consonants present before that vowel to the end of the word along with “ay”.
- Otherwise, postfix “ay” to the word because it doesn’t have any vowel.
- Form a new sentence using the
join()method and output it.
These are the steps following which we can easily convert any sentence into its corresponding Pig Latin form in Python.