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.

>>> st = "pencil programmer"
>>> print(st.split())
['pencil', 'programmer']

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:

st="pencil programmer"

print("First Letter of Each Word:")
for word in st.split():
    print(word[0])
    
print("Second Letter of Each Word:")
for word in st.split():
    print(word[1])
    
print("Third Letter of Each Word:")
for word in st.split():
    print(word[2])

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.

>>> st = "pencil programmer"
>>> for s in st.split():
>>>    print(s[10])
Traceback (most recent call last):
  File "<string>", line 5, in <module>
IndexError: string index out of range

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.

st = "pencil programmer"
n = 7

print(f"{n}th Letter of Each Word:")
for word in st.split():
    print(word[n] if n < len(word) else None)

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