How to Check if the Words of a String Begin with a Vowel or Consonant in Python



Python


In this article, we show how to check if the words of a string begin with a vowel or consonant in Python.

This may be used for real-world problems or may just be used for illustration purposes to see how this can be achieved.

In this article, we show how to do this.

We will loop through each word of a string with a for loop and then use an if statement to check to see whether the first letter in each word begins with a vowel or consonant.

The following code checks to see whether each word begins with a vowel or consonant.



So let's go over this code now. string1= "I went to the beach today. The beach was really good.I very much enjoyed it." splitstring= string1.split() newstring= '' for word in splitstring: if word[0] in ['a','e','i','o','u','A','E','I','O','U']: newstring += ("'" + word + "'") newstring += ' begins with a vowel\n' else: newstring += ("'" + word + "'") newstring += ' begins with a consonant\n'

So the first thing is, we have a string, string1.

You can see that each word is separated by a space, as words normally are in a sentence.

To be able to examine each word separately, we need to use the split() function to break up each word in the sentence into its own string. So we use the split() function on the string and store this result in the variable, splitstring.

We then have a variable, newstring, which we set equal to an empty string.

We then use a for loop to go through each word of the string that is broken.

We use a for loop to go through each word of the string.

The first letter of each word is represented by word[0].

So if word[0] is equal to a,e,i,o,u or A,E,I,O,U, then it begins with a consonant.

If you wanted to, you could use the lower() function to make the original string lowercase. That way, you would only have to check to see if the first letter is a lowercase vowel. But we chose not to do it that way. We chose to keep it the way it is and check lowercase and uppercase letters.

If the word begins with a vowel, we add it to the newstring variable wrapped within single quotes. We then put after it, begins with a vowel. The \n puts each word on a new line.

We then have an else statement. Else, the word begins with a consonant. Those are the only 2 options. The word either begins with a vowel or a consonant.

If it begins with a consonant, we do the same thing. We put the word within single quotes and then put after it, begins with a consonant. \ \n puts each word on a new line.

We then print out newstring and you can see the result above.

So this is how we can check to see if the words of a string begin with a vowel or consonant in Python.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...