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

Published: January 31, 2022

Updated: December 09, 2022

Tags: Python; Regular Expression;

DMCA.com Protection Status

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']

see also regex101