How to match a single character in python using Regular Expression?


A single character can be matched in python with using regular expression.

Regular expression is a sequence of characters that helps you to find a string or a set of string by using a search pattern. Regular expressions are also known as RegEx. Python provides the re module that is used to work with regular expression.

In this article, we will look at how to match a single character in python using regular expression. We use ‘.’ special character to match any single character.

Using findall() function

In the following example, let us assume ‘oats cat pan’ as a string. Where we need to match ‘at’ characters from the string.

Example 1

In the following example code, we use findAll() function to match a single character in python using regular expression. We begin by importing regular expression module.

import re

Then, we have used findall() function which is imported from the re module.

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

The re.findall() function returns a list containing all matches, that is list of strings that match with the character.

Output

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)

Output

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

Updated on: 08-Nov-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements