Python Program to convert a word into Pig Latin form using Functions
In this Python tutorial, we will learn how to convert a sentence into its Pig Latin form.
To do so, we shall be using:-
- Functions
- split() function in Python
- Substrings in Python
- Concatenation
We shall explain all of these in this Python tutorial.
Let us first see what exactly Pig Latin is!
Pig Latin form
Pig Latin is a language game where we alter English words into codes on the basis of certain rules:-
- Traverse the word till you reach a vowel. While doing so, there may be multiple vowels in the word, but always consider the first one.
- On reaching a vowel, consider the rest of the string beginning from that vowel and add that to a new empty string. Let us call this new string piglatin.
- Add the portion of the string from the beginning to where we encounter the vowel to piglatin.
- Add “ay” to the end of the string piglatin and we shall obtain our Pig Latin word.
Let us look at a some examples to reinforce the process:-
- Input:-
computer
Output:-
omputercay
In the word “computer”, the first vowel is o. So we consider the rest of the string “omputer” and put the rest of the string which is “c” in the front of the string and add “ay” to the end. As a result, we have our Pig Latin string “omputercay”.
- Input:-
proletariat
Output:-
oletariatpray
In the word “proletariat”, the first vowel is o. So we consider the rest of the string “oletariat” and put the rest of the string which is “pr” in the front of the string and add “ay” to the end. As a result, we have our Pig Latin string “oletariatpray”.
- Input:-
codespeedy
Output:-
odespeedycay
In the word “codespeedy”, the first vowel is o. So we consider the rest of the string “odespeedy” and put the rest of the string which is “c” in the front of the string and add “ay” to the end. As a result, we have our Pig Latin string “odespeedycay”.
Functions in Python
Function is a block of code that is executed when it is called. As a result it enhances many aspects of our code as shown below.
Why use functions in Python?
- Functions help reduce the complexity of the code
- It simplifies the interface of the code
- Code reusability increases as a function can be called multiple times.
In Python, functions are defined with the keyword def and return type of the function need not be mentioned.
Let us see an example of functions in Python from the following code:-
#This is a function called 'sum' which calculates the sum of two numbers def sum(a,b): sum = a+b return sum #Printing what the function 'sum' is returning print(sum(2,2)) print(sum(4,2))
As a result of the given code, the following output occurs:-
4 6
split() method in Python
split() method in Python breaks up a sentence into its constituent words on the basis of a particular separator. Here we are separating on the basis of the spaces in between the words.
How does the split() method in Python work?
#Initialising some strings sentence1 = "sun rises in the east" sentence2 = "coding in python is fun" sentence3 = "codespeedy is a great website" sentence4 = "strings are fun to work with" #using the split function words1 = sentence1.split() words2 = sentence2.split() words3 = sentence3.split() words4 = sentence4.split() #printing the words of the sentences after splitting them print("The words of the first sentence are::", words1) print("The words of the second sentence are::", words2) print("The words of the third sentence are::", words3) print("The words of the fourth sentence are::", words4)
Let’s look at the output:-
The words of the first sentence are:: ['sun', 'rises', 'in', 'the', 'east'] The words of the second sentence are:: ['coding', 'in', 'python', 'is', 'fun'] The words of the third sentence are:: ['codespeedy', 'is', 'a', 'great', 'website'] The words of the fourth sentence are:: ['strings', 'are', 'fun', 'to', 'work', 'with']
Here, Python has this facility via the split() function where we are getting a separate list based on the placement of whitespaces in between words.
I hope the working of the split() function in Python is clear to you now!
Substrings in Python(Slicing)
Python has a very cool feature which makes it easy to extract a portion of a string. Strings are sliced on the basis of the index numbers of the characters we want to extract from and to.
It follows the following template:-
string[start:end:step]
Here:-
- start is the index number from which the substring is considered.
- end is the index number to which we will be slicing the original string.
- Consider that the number given in step is n. Then n characters after the current characters is included and the characters in between are skipped. The default value of step is 1.
How does slicing of strings work in Python?
Let us take a look:-
#Initialise the string string = "CodeSpeedy" #Get the first 5 characters of a string print(string[0:5]) #Get a substring of length 3 from the 2nd character of the string print(string[1:4]) #Get the last character of the string print(string[-1]) #Get the last 3 characters of a string print(string[-3:]) #Get a substring which contains all characters except the last 3 characters and the 1st character print(string[1:-3])
Output:-
CodeS ode y edy odeSpe
I hope you understood how slicing of a string works!
Concatenation of Strings
String concatenation is the process of adding two strings together using the ‘+’ symbol to form a new string.
Let us look at the following Python Code to understand the same:-
s1 = "Python" s2 = "is an" s3 = "Object Oriented" s4 = "Programming Language" s5 = s1 + " " + s2 s6 = s3 + " " + s4 print(s5) print(s6) print(s5+" " +s6)
Output:-
Python is an Object Oriented Programming Language Python is an Object Oriented Programming Language
I hope concatenation is clear to you now!
Code and Output
Look at the following Python code to convert a sentence into Pig Latin:-
Code in Python to convert a word into Pig Latin form using Functions is given below:
#Function to check whether a character is a vowel or not def char_isVowel(c): vowel = ['A', 'E', 'I', 'O', 'U','a','e','i','o','u'] if c in vowel: return True else: return False #Function to convert a word to its PigLatin form def pigLatin(s): flag = False; vow_index = 0 for i in range(len(s)): if (char_isVowel(s[i])): vow_index = i flag = True; break; if (not flag): return s; pigLatin = s[vow_index:] + s[0:vow_index] + "ay" return pigLatin #Initialising a sentence sentence = "Python offers excellent readability and uncluttered simple to learn syntax which helps beginners understand coding" #Splitting the sentence into a list consisting of its words list = sentence.split() #Printing the original sentence print("The original sentence is:-") print(sentence) #Initialising an empty string for forming the PigLatin sentence pig_str = "" #Iterating over list for word in list: pig_str += " " + pigLatin(word) #Printing the PigLatin sentence print("The piglatin sentence is:-") print(pig_str)
Output:-
The original sentence is:- Python offers excellent readability and uncluttered simple to learn syntax which helps beginners understand coding The piglatin sentence is:- onPythay offersay excellentay eadabilityray anday uncluttereday implesay otay earnlay axsyntay ichwhay elpshay eginnersbay understanday odingcay
Please try to understand the given code using pen and paper before moving on to the explanation of the Python code given below!
Explanation of the Code
char_isVowel() function:-
- Consider a list vowel which contains all the vowels of the English alphabet in both upper and lower case.
- If a character of the argument passed to this function is present in the list vowel then this function returns True, else it returns False.
pigLatin() function:-
- Consider a flag and set it to False. If the word passed as argument does not have a vowel involved then we return the argument itself. Otherwise we return the Pig Latin word.
- Initialise a variable vow_index which will contain the index of the character where the first vowel occurs in the argument.
- Iterate over the argument passed to this function and when a vowel is encountered, the index is noted in vow_index and we break out of the iteration.
- Slice the string as per the rules of forming a Pig Latin word and form the word via concatenation.
- Return the string if the flag is True.
Rest of the code:-
- Initialise a sentence.
- Split the sentence into a list consisting of its words using the split() method in Python
- Print the original sentence.
- Initialise an empty string for forming the Pig Latin sentence.
- Iterate over list.
- Pass the elements of list into the pigLatin() function and form a sentence by including a space between the respective words.
- Print the Pig Latin sentence.
I hope this Python tutorial was useful for you!
Leave a Reply