Python find any character in string

Discover How to Find a Character in a String Using Python

python find character in string

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

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

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.

Источник

Check if String Contains Specific Characters in Python

In this article, we will learn how to check a string for specific characters in Python.

Table Of Contents

Method 1: Using in operator

We can use the in operator to check if a particular character exists in a given string or not. If it exists, the True is returned, otherwise False is returned. Let’s see some examples

In this example, we will consider the string – “Welcome to thisPointer” and check for the character – ‘t’ in it.

Читайте также:  Zerodivisionerror integer division or modulo by zero питон ошибка

Frequently Asked:

strValue = "Welcome to thisPointer" print("String - ", strValue) # Check for 't' in string strValue if 't' in strValue: print("Character 't' exists in the String") else: print("Character 't' does not exists in the String")
String - Welcome to thisPointer Character 't' exists in the String

We can see that character – ‘t’ is found in strValue.

In this example, we will consider the string – “Welcome to thisPointer” and check the existence of multiple characters in it. For ir, we will iterate over all characters in list, and for each character, check if it exists in the string or not. For example,

strValue = "Welcome to thisPointer" print("String - ", strValue) # List of characters listOfCharacters = ['W','e','P','Y'] # Check if characters in the list exists in the above string or not for ch in listOfCharacters: # Check if character ch exists in string strValue if ch in strValue: print("Character \"", ch, "\" exists in the String") else: print("Character \"", ch, "\" does not exists in the String")
String - Welcome to thisPointer Character " W " exists in the String Character " e " exists in the String Character " P " exists in the String Character " Y " does not exists in the String

We can see that characters – ‘W’,’e’ and ‘P’ were found in string strValue, but character ‘Y’ was not found in the string.

Method 2: Using contains() method

The contains() method of string class, checks if a particular character exists in the given string or not. If it exists, True is returned, otherwise False is returned.

In this example, we will consider the string – “Welcome to thisPointer” and check for the character – ‘t’ in it.

strValue = "Welcome to thisPointer" print("String - ", strValue) # A character that need to checked ch = 't' # Check if character ch exists in string strValue if strValue.__contains__(ch): print("Character \"", ch, "\" exists in the String") else: print("Character \"", ch, "\" does not exists in the String")
String - Welcome to thisPointer Character " t " exists in the String

We can see that character – ‘t’ exists in the string.

In this example, we will consider the string – “Welcome to thisPointer” and check the existence of particular characters.

strValue = "Welcome to thisPointer" print("String - ", strValue) # List of characters listOfCharacters = ['W','e','P','Y'] # Check if characters in the list exists in the above string or not for ch in listOfCharacters: # Check if character ch exists in string strValue if strValue.__contains__(ch): print("Character \"", ch, "\" exists in the String") else: print("Character \"", ch, "\" does not exists in the String")
String - Welcome to thisPointer Character " W " exists in the String Character " e " exists in the String Character " P " exists in the String Character " Y " does not exists in the String

We can see that characters – ‘W’,’e’ and ‘P’ are found in string, but the character ‘Y’ is not found in the string.

Method 2: Using find() method

The string class provides a member function find(). It accepts a string or a character as an argument, and returns the lowest index of the given string/character in the calling string object. If string/character does not exists in the calling string object, then it returns -1.

We can use this to check if a character exists in a string or not. For that, we just need to pass the character in find() function, and check if returned value is not -1. Let’s see some examples,

Читайте также:  Type is record oracle java

In this example, we will consider the string – “Welcome to thisPointer” and check for the character – ‘t’ in it.

strValue = "Welcome to thisPointer" print("String - ", strValue) # A character that need to be serached ch = 't' # Check if character ch exists in string strValue if strValue.find(ch) != -1: print("Character \"", ch, "\" exists in the String") else: print("Character \"", ch, "\" does not exists in the String")
String - Welcome to thisPointer Character " t " exists in the String

We can see that character – ‘t’ is found in string1.

In this example, we will consider the string – “Welcome to thisPointer” and check the existence of particular characters.

strValue = "Welcome to thisPointer" print("String - ", strValue) # List of characters listOfCharacters = ['W','e','P','Y'] # Check if characters in the list exists in the above string or not for ch in listOfCharacters: # Check if character ch exists in string strValue if strValue.find(ch) != -1: print("Character \"", ch, "\" exists in the String") else: print("Character \"", ch, "\" does not exists in the String")
String - Welcome to thisPointer Character " W " exists in the String Character " e " exists in the String Character " P " exists in the String Character " Y " does not exists in the String

We can see that characters – ‘W’,’e’ and ‘P’ exists in the string, but the character ‘Y’ is not found in the string.

Summary

We learned to check a string for specific character/characters using three different techniques. Thanks.

Share your love

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

Оцените статью