Python check if string has character

Python: Check if a character or substring is in a string

How to check if a character / substring is in a string or not #

Let me start with a little history about myself. I have been developing on the Web for more than five years now — in PHP. Yes, in goddamn PHP! I had been exposed to Python much earlier, but for some strange reason I never made the effort to learn it or use it. If I had learnt Python earlier, I wouldn’t be struggling to to check if a substring exists in a string or not, today.

On the brighter side, I realize what a beautifully designed language Python is; and I make notes in the form of posts like this which other Python beginners might find handy. I am gonna be making a huge lot of useful posts related to Python among other stuff on my website, which is good.

Coming back to the topic «how do you check if a substring or character is there in a string». A character is also a substring technically, anyway, this is how you do it.

if 'c' in 'Python': print 'YES' else: print 'NO'

Isn’t that so beautifully simple?

When faced with the problem, my brain being damaged temporarily by PHP, I started to think in terms of PHP’s own substr() and strpos() functions, and started looking for similar functions in Python. I did get them, str.find() and str.index() , but turns out they are best used when you want to know the position of the substring. For checking if a substring or character exists in a string, you use the in operator instead.

Excuse me, but Python is a fuckin beautiful language!

Exercise #

  1. What is the opposite of the in operator?
  2. What is the difference between str.find() and str.index() ?

References #

  • Online ASCII Converter/Generator This online ASCII code generator converts string to ASCII characters and ASCII characters to string. Jul 2, 2019
  • Online Base64 Encoder-Decoder Online tool for encoding plain text to Base64 and decoding Base64-encoded characters to plain text. Jul 14, 2019
  • Python: Length or size of list, tuple, array How to get the length of a list or tuple or array in Python Let me clarify something at the beginning, by array, you probably mean list in Python. list is the equivalent of arrays in JavaScript or PH. Jul 30, 2011
Читайте также:  Javascript script error cdn

Источник

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.

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.

Читайте также:  Javascript создание объекта new

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,

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.

Читайте также:  Php перевести секунды минуты часы

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.

Источник

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