Get first letter of every word in String in Python

In this article, we will discuss how to get first letter of every word in String in Python.

Table Of Contents

Introduction

Suppose we have a string, like this,

"This is a big string to test."

We want to create a list, containing the first letter of every word in the String. Like this,

['T', 'i', 'a', 'b', 's', 't', 't']

There are different ways to do this. Let’s discuss them one by one.

Method 1: Using For Loop

Follow these steps to get first letter of each word in a string,

  • Create an empty list to hold the first letter of each word of string.
  • Split the string into a list of words using the split() method of string class.
  • Iterate over each word in the list, using a for loop, and for each word, append its first letter to the list created in first point.
  • Now, this new list will have the first letter of each word from the string.

Let’s see an example,

strValue = "This is a big string to test."

# Split string into a list of words
listOfWords = strValue.split()

# List to contain first letter of each word
listOfLetters = []

# Iterate over all words in list
for word in listOfWords:
    # Select first letter of each word, and append to list
    listOfLetters.append(word[0])

print(listOfLetters)

Output:

['T', 'i', 'a', 'b', 's', 't', 't']

We create a list, and filled it with the first letter of every word from the string.

Method 2: Using List Comprehension

Split the string into a list of word using split() method of string class. Then iterate over all words in the list, and from each word select the first letter. Do, all this inside the List Comprehension, and build a list of first letters of each word. Let’s see an example,

strValue = "This is a big string to test."

# Select first letter of each word, and append to list
listOfLetters = [ word[0] for word in strValue.split()]

print(listOfLetters)

Output:

['T', 'i', 'a', 'b', 's', 't', 't']

We create a list, and filled it with the first letter of every word from the string.

Summary

We learned about two different ways to fetch the first letter of each word in a string in Python. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top