×

Check Letter in a String Python

Checking a specific letter or a character in a given string or a string which is taken as an input from the user is possible in Python in broadly three types they are:

i)Using 'in' operator

ii)Using str.find() function

iii)Using Regex

Let us now discuss each method in detail, starting with 'in' operator in Python to check for a letter in the string

1. Using in Operator

We will discuss checking the letter in two ways, one by pre-defining a variable with a certain string and the other by taking a user input using the pre-defined input function available in Python by passing a prompt into the braces.

Code  

variable_1 = 'javatpoint'
if 't' in variable_1:
    print('letter exists')
else:
    print('letter doesnot exist')

Output

letter exists

In the above code, we see that we have declared the variable as variable_1 with a string value as 'javatpoint' and by using the if and else condition, we are checking if the letter 't' exists in the string or not. Since the letter t exists in the variable we passed, it returned the if condition's print statement saying the letter exists.

Code

variable_1 = input('enter the word to check the letter : ')
if 'engi' in variable_1:
    print('letter exists')
else:
    print('letter doesnot exist')

Output

enter the word to check the letter : software engineer
letter exists

Now in the above code, we are checking for not a single letter but a group of characters to check the functionality of the in operator. We see that using the input function in the variable_1 and prompt saying enter the word to review the letter, the input from the user will be taken as soon as the code runs. By using the if and else condition, we are checking for the group of characters 'engi', which are a part of the word software engineer. When the code is set to run compiler asks for input; assume in this case we are giving input as a software engineer as the group of characters are present in the input variable, the condition gets triggered and executes the block of code below in the print statement saying that the letter exists.

2.Using str.find() Function

Python is known for its easiness, being handy and effectively managing code. We have many built-in functions that make the programming language stand out amongst others, so in our case, the str.find() function makes our job easy here. The short form of the function stands for string find. Not necessary that we have to use str as the prefix. We can use anything like 's' or 'string'. The catch here is to use the dot find function ideally.

Code

variable_1 = 'javatpoint'
letter = 'poi'
if variable_1.find(letter) !=-1:
    print('letter exists')
else:
    print('letter doesnot exist')

Output

letter exists

In the above block of code, we see that we have declared the variable_1 with the value javatpoint and another variable with the value of a group of characters 'poi' now, as the letter variable exists in the variable_1, the if condition gets executed and prints that letter exists.

3. Using Regex

The third primary approach to finding a letter in a string is using the Regex. Regex stands for regular expression. When we import the 're' module, we can start using the regular expressions at the beginning of the code.

Code

import re


text = 'match is cancelled due to rain'
x = re.search('^match.*rain',text)


if x:
    print('yes the text starts with match and ends with rain')
else:
    print('no it doesnot start with match and doesnot ends with rain')

Output

yes the text starts with match and ends with rain

As we see in the above code, instead of checking for a letter or a group of letters, we check if the text starts with a particular word and ends with a specific term.


Related Topics

Loan calculator using Tkinter in Python

Tkinter: Tkinter, part of all common Python distributions, is the de facto method for creating Graphical User Interfaces (GUIs) in Python. The only framework included in the Python standard library is...

4 minutes read.

Isreal() Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

4 minutes read.

Python List reverse() method

 Python List reverse() method The list.reverse () method in Python reverses the elements of the list in place. Syntax list.reverse() Parameter NA Example 1 # Python program explaining # the list.reverse() method weekList = ['Sun','Thurs','Mon','Fri', 'Tues', 'Wed'] print("Actual week list: ",weekList) #...

1 minute read.

How to Open a file in python with Path

In this tutorial, we will see rather than the traditional way of opening a file by locating or navigating it from our desktops; we will learn how to open the...

2 minutes read.

How to get current date in python?

How to get current date in python? In Python programming language, date and time are not just a data form, but it is possible to import a method called datetime to operate...

3 minutes read.

Mrcnn Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

6 minutes read.

Python Dictionary Methods

Python Dictionary Methods Python has a set of built-in methods that dictionary objects can call. All the python dictionary methods are as follow: Methods Description clear() The dictionary.clear() method removes all the elements...

3 minutes read.

Python String rfind() method

The string. rfind() method in Python returns the highest index in the string if the substring sub is found else it returns -1 if the substring is not found. Syntax string.rfind(sub [,start [,end]]) Parameter sub: This parameter...

2 minutes read.

Read numpy array in Python

Numpy is a numerical python that deals with multidimensional arrays mostly used in storing multiple values. Python's core scientific computing package is called NumPy. This Python library provides multidimensional array...

9 minutes read.

Python Dictionary get() method

Python Dictionary get() method The dictionary.get() method returns the value of the item with the specified key. Syntax dictionary.get(keyname, value) Parameter keyname- This parameter represents the key to be searched in the dictionary. value- The parameter...

1 minute read.

Python program to find the area of a circle

Python program to find the area of a circle This article will discuss how to find the area of a circle in Python with a given radius. The area of a...

2 minutes read.

Python str() function

Python str() function The str() function in Python converts the specified value into a string. Syntax class str(object='')           or class str(object=b'', encoding='utf-8', errors='strict') Parameter object:  This parameter represents any object to convert the given...

1 minute read.

Python slice()

Python slice() class The slice() class return a slice object representing the set of indices specified by range(start, stop, step).  Syntax class slice(stop)          or class slice(start, stop[, step]) Parameter Start: This parameter represents an integer number specifying at...

1 minute read.

Python Break Statement

In Python, loops are used to automate and repeat processes in an effective manner. However, there may be occasions when you wish to entirely exit the loop, skip an iteration,...

2 minutes read.

Google Chrome API in Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Python Selectors

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

4 minutes read.

List Comprehension in Python3

List A list in python is a complex data type, and a list is a collection of the number of data. The data variable may or may not be of the...

5 minutes read.

Python String zfill() method

Python String zfill() method The string.zfill() method in Python returns a copy of the string while adding the zeros (0) at the beginning of the string, until it reaches the specified...

1 minute read.

Python String index() method

Python String index() method The string.index() method in Python finds the lower index of the first occurrence of the specified value or raise a ValueError if the substring is not found. Syntax index(sub[, start[, end]]) Parameter sub:...

2 minutes read.

Artificial intelligence mini projects with source code in Python

Project Name: Movie recommendation system A recommendation provides customers with relevant information related to their searches. Before the recommendation system, the most common method of purchasing was to rely on the...

4 minutes read.