Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Match a Single Character in Python Using Regular Expression



A single character can be matched in Python using a regular expression. A regular expression is a sequence of characters that helps you find a string or a set of strings using a search pattern. Regular expressions are also known as RegEx. Python provides the re module that is used to work with regular expressions -

Using findall() function

We use findall() searches for the strings matching the specified pattern in the given string and return all the matches in the form of a list of strings or tuples. 

Example 1

In the following example, we begin by importing the regular expression module. Then, we used the findall() function, to search the substring "at" in the string 'oats cat pan'.

import re
string = 'oats cat pan'
res = re.findall(r'.at', string)
print(res)

On executing the above program, the following output is obtained -

['oat', 'cat']

Example 2

To match and print any single character in the given string using a Python regular expression, use the following code. Any single character in the given string is matched by this.

import re
String = 'Python program'
result = re.findall(r'.', String)
print ('The single characters in the strings are:',result)

The following output is obtained from the above code -

The single characters in the strings are: ['P', 'y', 't', 'h', 'o', 'n', ' ', 'p', 'r', 'o', 'g', 'r', 'a', 'm']

Example 3

In the following code, we use the findall() function to find words that have a vowel as the second character.

import re
string = 'man men sun run fun'
res = re.findall(r'.u.', string)
print(res)

The output is as follows -

['sun', 'run', 'fun']

Example 4

This example shows how to find any 3-letter word ending with "an" from the given string. 

import re
text = 'fan can ran tan plan'
matches = re.findall(r'.an', text)
print('Matched words are:', matches)

The result of the above program will be -

Matched words are: ['fan', 'can', 'ran', 'tan']

Example 5

In this example, we are going to print all characters one by one using findall(), which matches any single character, including space.

import re
sentence = 'AI is fun!'
characters = re.findall(r'.', sentence)
print('Characters found:', characters)

The output for the above program is -

Characters found: ['A', 'I', ' ', 'i', 's', ' ', 'f', 'u', 'n', '!']
Updated on: 2025-04-24T10:46:44+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements