Discover How to Find a Character in a String Using Python

This article explains several ways through which one can determine the presence of a character in a string in Python. You can opt for the in operator, any keyword, find(), index(), count(), etc., to check whether the character is present in a string or not.

Ways of finding characters in Python string

One can find a character in a string in Python through several ways, some of which are by using in operator, Regex character matching, any method, index() method, find() Method, __contains__() function, etc.

in operator

With the help of In, you can check for the presence of a character without taking much time. The below-stated example makes this statement clear. The result is in the form of boolean values, i.e., True or False. It is case-sensitive.

str="india
if 'i' in str:
   print("found")

In this example, the left character- which is to be matched, matches with the original string, and you get true as a result. Otherwise, the result is False.

__contains__() function

character in string in Python
character in string in Python

It is considered to be a subdivision of the in-operator. It shouldn’t be used directly in the program. The output is in the form of either True or False. See the example to know more about the usage of the __contains__() function:

a1= "hello world"
a2 = "w"
output = a1.__contains__(a2)
print("Output : ",output)
#answer will be True here as w exists in the a1 string.

It is used for character and string matching both.

See this link to know the best Ways to Use Python String __contains__() Method(Opens in a new browser tab)

find() Method

It returns -1 if the character if it finds a character in the string. Otherwise, it returns the index of the position where the character is a. It has three arguments:

  • Sub for the character here
  • Start with the starting index of the part of the string you want to take for searching.
  • The end for the last index value of the part of the string to be searched

Noteworthy is the fact that a sub-argument is necessary while the other two are optional. In case you don’t provide a value for start and end, and the compiler assumes it to be 0 and length -1.

char='get it'
result = char.find('i')

The output will be four here.

index() method

The output of this method is the position where you will obtain the character. It can extend to string searching also. Just like find(), it has start and end arguments. However, if the character is not present in the string, it will give an error. It doesn’t give -1 as a result. So, one should use a try-except block to make the code error-free.

try:
    "A garden".index("g")
except ValueError:
    print("not found")
else:
    print(str.index("g"))

any method

Here, by using any, we can compare the character with other letters present in the string. The conventional if-else method is faster than this one. It gives the result as a boolean True or False.

any(i in 'a' for i in 'abc') 
#will be True

Know more about Python Any | [Explained] any() Function in Python
(Opens in a new browser tab)

Regex character matching

You may consider Regex as one of the simplest pattern-matching ways. It is capable enough to match any character. Supposedly, we want to know whether an alphabet is a part of the string; we can take note of the following example:

import re
string_a= "an apple 123"
print(bool(re.match('^[a-zA-Z]+$', string_a)))

Find and replace a character in the Python string

Finding a character and replacing it with another character in a Python string may be likely. For this, replace() function should be used. The replace() function has three arguments- the character which needs to be replaced, the new character, and the number of times replacement has to be done. This works with the given example:

strA= "this is the best Python blog. "
#you have to replace "t" with "T" only one time
print(strA.replace("t", "T",1))

Hence, as per this example, the output will be:

This is the best Python blog. 

Find the character count in a string

If you want to know the number of times a character has occurred in the given string, the count() function will meet your needs.

STR = "this is the best Python blog."
Ans= STR.count('t') 
print(Ans)

If you have to find the number of occurrences of ‘t’ in this string, you will get four as the Ans value.

Find a character from the end

To find the character from the end, go for rfind() function. It will give the index where you got the last occurrence of the letter. It works for substrings too. You can also provide a start and end value so that the compiler only searches for the character in that interval.

text = "Here are forty notebooks."
Ans = text.rfind("s", 5, 18)
print(Ans)
#Ans is -1 as in this range, s isn't present. 

Find a character in a pandas string

It works in the Series.str.contains() format. Once you have a dataframe, you might want to find whether a character occurs in the string. So you can pass the character as the argument. It also works for a substring. It includes case=True if you want to match it sensitively, Regex for matching regex patterns, and na to complete values that don’t exist.

Use it on a column where you must check for the character’s presence.

print(df.col_name.str.contains('H'))

FAQs

How can one avoid errors using the find and index method during character searching?

Both these methods are case-sensitive. Thus, you can include the .lower() function. It will do the correct matching.

Conclusion

With the help of this article, one can easily practice how we will know the presence of a character in a string. It can use find, index, any, or contains functions along with an operator.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments