How to extract first letter of each word in a sentence with python using a regular expression ?

Active January 31, 2022    /    Viewed 266    /    Comments 0    /    Edit


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:

re.findall(r'\b([a-zA-Z]|\d+)', s)

gives

['H', 'h', 'a', 'y', 't']

Note that

l = re.findall(r'\b([a-zA-Z]|\d+)', s)

print(type(l) )

returns a list

<class 'list'>

To convert letters to lower case"

l = [e.lower() for e in l]

print( l )

gives then

['h', 'h', 'a', 'y', 't']

To join all letters"

'.'.join(l)

gives

h.h.a.y.t

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 )

gives

['h', 'h', 'a', 'y', 't']

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()] )

gives

['h', 'h', 'a', 'y', 't']

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!



Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount