- How to extract first letter of each word in a sentence with python using a regular expression ?
- Using a python regular expression
- Without using a regular expression
- Benjamin
- Get first letter of every word in String in Python
- Introduction
- Frequently Asked:
- Method 1: Using For Loop
- Method 2: Using List Comprehension
- Summary
- Related posts:
- Share your love
- Leave a Comment Cancel Reply
- Terms of Use
- Disclaimer
- First letter word python
- # Table of Contents
- # Get the first character of each string in a List in Python
- # Get the first character of each string in a List using for loop
- # Get first character of first string in a List in Python
- # Handling a case where the list is empty or the first string is empty
- # Get the first letter of each word in a String in Python
- # Get the first letter of each word in a String using a for loop
- # Additional Resources
How to extract first letter of each word in a sentence with python using a regular expression ?
Example of how to extract first letter of each word in a sentence with python using a regular expression:
Using a python regular expression
Let’s consider the following sentence:
import re
s = 'Hello, how are you today'
to extract first letter of each word:
l = re.findall(r'\b([a-zA-Z]|\d+)', s)
print(type(l) )
To convert letters to lower case»
l = [e.lower() for e in l]
print( l )
Another example with a number in the sentence:
s = 'Hello, how are you today, 1234'
l = re.findall(r'\b([a-zA-Z]|\d+)', s)
to select only letters a solution is to use isalpha():
l = [e.lower() for e in l if e.isalpha()]
print( l )
Without using a regular expression
Another solution using only a list comprehension:
s = 'Hello, how are you today, 1234'
l = [e[0].lower() for e in s.split()]
print( [e[0].lower() for e in l if e.isalpha()] )
Benjamin
Greetings, I am Ben! I completed my PhD in Atmospheric Science from the University of Lille, France. Subsequently, for 12 years I was employed at NASA as a Research Scientist focusing on Earth remote sensing. Presently, I work with NOAA concentrating on satellite-based Active Fire detection. Python, Machine Learning and Open Science are special areas of interest to me.
Skills
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,
There are different ways to do this. Let’s discuss them one by one.
Frequently Asked:
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.
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)
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)
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.
Related posts:
Share your love
Leave a Comment Cancel Reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
Terms of Use
Disclaimer
Copyright © 2023 thisPointer
To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
First letter word python
Last updated: Feb 22, 2023
Reading time · 6 min
# Table of Contents
# Get the first character of each string in a List in Python
To get the first character of each string in a list:
- Use a list comprehension to iterate over the list.
- Access each string at index 0 and return the result.
- The new list will contain the first character of each list item.
Copied!my_list = ['bobby', 'hadz', 'com'] new_list = [item[0] for item in my_list] print(new_list) # 👉️ ['b', 'h', 'c']
We used a list comprehension to iterate over the list.
List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.
On each iteration, we access the current item at index 0 and return the result
Python indexes are zero-based, so the first character in a string has an index of 0 , and the last character has an index of -1 or len(my_str) — 1 .
The new list contains the first character of each string in the original list.
Alternatively, you can use a for loop.
# Get the first character of each string in a List using for loop
This is a three-step process:
- Declare a new variable that stores an empty list.
- Use a for loop to iterate over the original list.
- Append the first character of each string to the new list.
Copied!my_list = ['bobby', 'hadz', 'com'] new_list = [] for item in my_list: new_list.append(item[0]) print(new_list) # 👉️ ['b', 'h', 'c']
We used a for loop to iterate over the list.
On each iteration, we use the list.append() method to append the first character of the current string to the new list.
The list.append() method adds an item to the end of the list.
Copied!my_list = ['bobby', 'hadz'] my_list.append('com') print(my_list) # 👉️ ['bobby', 'hadz', 'com']
The method returns None as it mutates the original list.
Which approach you pick is a matter of personal preference. I’d use a list comprehension as I find them quite direct and easy to read.
# Get first character of first string in a List in Python
Use two sets of square brackets to get the first character of the first string in a list.
The first set of square brackets returns the first element in the list and the second set returns the first character in the string.
Copied!my_list = ['bobby', 'hadz', 'com'] first = my_list[0][0] print(first) # 👉️ 'b' print(my_list[0][1]) # 👉️ 'o'
Python indexes are zero-based, so the first item in a list has an index of 0 , and the last item has an index of -1 or len(my_list) — 1 .
The first set of square brackets is used to access the first item in the list.
Copied!my_list = ['bobby', 'hadz', 'com'] print(my_list[0]) # 👉️ bobby print(my_list[0][0]) # 👉️ b
The second set of square brackets is used to access the first character in the string.
# Handling a case where the list is empty or the first string is empty
If you try to access a list or a string at an index that doesn’t exist, you’d get an IndexError exception.
You can use a try/except statement if you need to handle the exception.
Copied!my_list = ['', 'hadz', 'com'] try: print(my_list[0][0]) except IndexError: # 👇️ this runs print('The specified index is out of range')
The first string in the list is empty, so trying to access it at index 0 raises an IndexError , which is then handled by the except block.
You can use the same approach to get the first N characters of the first string in a list.
Copied!my_list = ['bobby', 'hadz', 'com'] first = my_list[0][:1] print(first) # 👉️ 'b' first_two = my_list[0][:2] print(first_two) # 👉️ 'bo' first_three = my_list[0][:3] print(first_three) # 👉️ 'bob'
The syntax for string slicing is my_str[start:stop:step] .
The slice my_str[:1] starts at index 0 and goes up to, but not including index 1 , so it only selects the first character of the string.
When the start index is omitted, the slice starts at index 0 .
If you need to get the first character of each string in the list, use a list comprehension.
Copied!my_list = ['bobby', 'hadz', 'com'] first_chars = [item[0] for item in my_list] print(first_chars) # 👉️ ['b', 'h', 'c']
We used a list comprehension to iterate over the list of strings.
List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.
On each iteration, we access the current string at index 0 and return the first character.
The new list contains the first character of each string in the list.
# Get the first letter of each word in a String in Python
To get the first letter of each word in a string:
- Use the str.split() method to split the string into a list of words.
- Use a list comprehension to iterate over the list.
- Access each word at index 0 and return the result.
Copied!my_str = 'my site is bobbyhadz.com' my_list = [word[0] for word in my_str.split()] print(my_list) # 👉️ ['m', 's', 'i', 'b']
We used the str.split() method to split the string into a list of words.
The str.split() method splits the string into a list of substrings using a delimiter.
Copied!my_str = 'my site is bobbyhadz.com' # 👇️ ['my', 'site', 'is', 'bobbyhadz.com'] print(my_str.split())
When no separator is passed to the str.split() method, it splits the input string on one or more whitespace characters.
We used a list comprehension to iterate over the list.
List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.
On each iteration, we access the current word at index 0 and return the result.
Copied!my_str = 'my site is bobbyhadz.com' my_list = [word[0] for word in my_str.split()] print(my_list) # 👉️ ['m', 's', 'i', 'b']
Python indexes are zero-based, so the first character in a string has an index of 0 , and the last character has an index of -1 or len(my_str) — 1 .
The new list contains the first letter of each word in the string.
Alternatively, you can use a for loop.
# Get the first letter of each word in a String using a for loop
This is a three-step process:
- Use the str.split() method to split the string into a list of words.
- Use a for loop to iterate over the list.
- Append the first letter of each word to a new list.
Copied!my_str = 'my site is bobbyhadz.com' my_list = [] for word in my_str.split(): my_list.append(word[0]) print(my_list) # 👉️ ['m', 's', 'i', 'b']
We first used the str.split() method to split the string into a list of words and used a for loop to iterate over the list.
On each iteration, we append the first letter of the current word to a new list.
The list.append() method adds an item to the end of the list.
Copied!my_list = ['bobby', 'hadz'] my_list.append('com') print(my_list) # 👉️ ['bobby', 'hadz', 'com']
The method returns None as it mutates the original list.
Which approach you pick is a matter of personal preference. I’d use a list comprehension as I find them quite direct and easy to read.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.