Problem: How to access or print the nth letter of every word in the given string using Python programming language?

To get the nth letter of every word in the given sentence, we first have to extract words from the sentence.

We can easily achieve this using the Python split() method.

split() method in Python returns a list of words by splitting the sentence on the basis of the specified separator. If the separator is not specified, it breaks the string on white space.

After we get a list of words, we can loop through the list and fetch the nth letter of every word using the indices.

Here is an example in which we are printing the 1st, 2nd, and 3rd letter of every word:

Output:

First Letter of Each Word:
p
p
Second Letter of Each Word:
e
r
Third Letter of Each Word:
n
o


The above method works fine, but if we try to access the letter which is out of the range of any word could cause an exception.

Best Practice for Accessing the nth letter

Better first check whether the value of n is less than or equal to the length of the word or not, if yes then only print the nth letter.

Output:

7th Letter of Each Word:
None
m


In this programming example, we learned to access and print the nth letter of every word of a string in Python programming language.

Leave a Reply

3 × one =