How to check if specified Character is in String?
Python - Check if specified character is in string
To check if a specified character is present in given string in Python, use Python in keyword with If conditional statement.
Sample Code Snippet
The following is a simple code snippet to check if the character ch is in the string name.
if ch in name:
#codeExample
In the following example, we take a character ch and a string name, and check if the character is present in the string.
Python Program
name = 'apple'
ch = 'p'
if ch in name:
print(ch, 'is present in', name)
else:
print(ch, 'is not present in', name)Output
p is present in appleWe can read the character and the string from user using input() function, and check if the character is present in the string or not.
Python Program
name = input('Enter string : ')
ch = input('Enter character : ')
if ch in name:
print(ch, 'is present in', name)
else:
print(ch, 'is not present in', name)Output#1
Enter string : apple
Enter character : e
e is present in appleOutput#2
Enter string : apple
Enter character : m
m is not present in appleSummary
In this tutorial of Python Examples, we learned how to check if specific character is present in the string or not, using Python in keyword.