The Wayback Machine - https://web.archive.org/web/20240930163939/https://www.geeksforgeeks.org/python-program-check-string-contains-special-character/
Open In App

Program to check if a string contains any special character

Last Updated : 08 Apr, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a string, the task is to check if that string contains any special character (defined special character set). If any special character is found, don’t accept that string.

Examples : 

Input: Geeks$For$Geeks
Output: String is not accepted.

Input: Geeks For Geeks
Output: String is accepted

Approach 1: Using regular expression

  1. Make a regular expression(regex) object of all the special characters that we don’t want
  2. Then pass a string in the search method. 
  3. If any one character of the string is matching with the regex object 
  4. Then search method returns a match object otherwise returns None.

Below is the implementation: 

C++
// C++ program to check if a string 
// contains any special character

// import required packages
#include <iostream> 
#include <regex> 
using namespace std; 

// Function checks if the string 
// contains any special character
void run(string str)
{
    
    // Make own character set 
    regex regx("[@_!#$%^&*()<>?/|}{~:]");

    // Pass the string in regex_search 
    // method
    if(regex_search(str, regx) == 0)
        cout << "String is accepted";
    else
        cout << "String is not accepted.";
} 

// Driver Code 
int main() 
{ 
    
    // Enter the string 
    string str = "Geeks$For$Geeks"; 
    
    // Calling run function
    run(str); 

    return 0; 
}

// This code is contributed by Yash_R
Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args)
    {
        String str = "Geeks$For$Geeks";
        Pattern pattern
            = Pattern.compile("[@_!#$%^&*()<>?/|}{~:]");
        Matcher matcher = pattern.matcher(str);

        if (!matcher.find()) {
            System.out.println("String is accepted");
        }
        else {
            System.out.println("String is not accepted");
        }
    }
}// this code is contributed by devendrasalunke
Python3
# Python3 program to check if a string
# contains any special character

# import required package
import re

# Function checks if the string
# contains any special character
def run(string):

    # Make own character set and pass 
    # this as argument in compile method
    regex = re.compile('[@_!#$%^&*()<>?/\|}{~:]')
    
    # Pass the string in search 
    # method of regex object.    
    if(regex.search(string) == None):
        print("String is accepted")
        
    else:
        print("String is not accepted.")
    

# Driver Code
if __name__ == '__main__' :
    
    # Enter the string
    string = "Geeks$For$Geeks"
    
    # calling run function 
    run(string)
C#
// C# program to check if a string
// contains any special character

using System;
using System.Text.RegularExpressions;

class Program {
    // Function checks if the string
    // contains any special character
    static void Run(string str)
    {
        // Make own character set
        Regex regex = new Regex("[@_!#$%^&*()<>?/|}{~:]");
        // Pass the string in regex.IsMatch
        // method
        if (!regex.IsMatch(str))
            Console.WriteLine("String is accepted");
        else
            Console.WriteLine("String is not accepted.");
    }

    // Driver Code
    static void Main()
    {
        // Enter the string
        string str = "Geeks$For$Geeks";

        // Calling Run function
        Run(str);

        Console.ReadLine();
    }
}
JavaScript
function hasSpecialChar(str) {
  let regex = /[@!#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/;
  return regex.test(str);
}

let str = "Geeks$For$Geeks";
if (!hasSpecialChar(str)) {
  console.log("String is accepted");
} else {
  console.log("String is not accepted");
}
PHP
<?Php
// PHP program to check if a string 
// contains any special character 

// Function checks if the string 
// contains any special character 
function run($string)
{
    $regex = preg_match('[@_!#$%^&*()<>?/\|}{~:]', 
                                         $string);
    if($regex) 
        print("String is accepted"); 
        
    else
        print("String is not accepted.");
} 

// Driver Code 

// Enter the string 
$string = 'Geeks$For$Geeks';

// calling run function
run($string);

// This code is contributed by Aman ojha
?>

Output
String is not accepted.

Method:  To check if a special character is present in a given string or not, firstly group all special characters as one set. Then using for loop and if statements check for special characters. If any special character is found then increment the value of c. Finally, check if the c value is greater than zero then print string is not accepted otherwise print string is accepted. 

C++
// C++ code
// to check if any special character is present
// in a given string or not
#include <iostream>
#include <string>
using namespace std;

int main()
{

    // Input string
    string n = "Geeks$For$Geeks";
    int c = 0;
    string s
        = "[@_!#$%^&*()<>?}{~:]"; // special character set
    for (int i = 0; i < n.size(); i++) {

        // checking if any special character is present in
        // given string or not
        if (s.find(n[i]) != string::npos) {
            // if special character found then add 1 to the
            // c
            c++;
        }
    }

    // if c value is greater than 0 then print no
    // means special character is found in string
    if (c) {
        cout << "string is not accepted";
    }
    else {
        cout << "string is accepted";
    }

    return 0;
}

// This code is contributed by uomkar369.
Java
// Java code to check if any special character is present
// in a given string or not
import java.util.*;
class Main {
    public static void main(String[] args)
    {
        // Input string
        String n = "Geeks$For$Geeks";
        int c = 0;
        String s = "[@_!#$%^&*()<>?}{~:]"; // special
                                           // character set
        for (int i = 0; i < n.length(); i++) {

            // checking if any special character is present
            // in given string or not
            if (s.indexOf(n.charAt(i)) != -1) {
                // if special character found then add 1 to
                // the c
                c++;
            }
        }

        // if c value is greater than 0 then print no
        // means special character is found in string
        if (c > 0) {
            System.out.println("string is not accepted");
        }
        else {
            System.out.println("string is accepted");
        }
    }
}
Python3
# Python code
# to check if any special character is present
# in a given string or not

# input string
n = "Geeks$For$Geeks"
n.split()
c = 0
s = '[@_!#$%^&*()<>?/\|}{~:]'  # special character set
for i in range(len(n)):
    # checking if any special character is present in given string or not
    if n[i] in s:
        c += 1   # if special character found then add 1 to the c

# if c value is greater than 0 then print no
# means special character is found in string
if c:
    print("string is not accepted")
else:
    print("string accepted")

# this code is contributed by gangarajula laxmi
C#
using System;

class Program {
    static void Main(string[] args)
    {
        // Input string
        string n = "Geeks$For$Geeks";
        int c = 0;
        string s = "[@_!#$%^&*()<>?}{~:]"; // special
                                           // character set

        for (int i = 0; i < n.Length; i++) {
            // checking if any special character is present
            // in given string or not
            if (s.IndexOf(n[i]) != -1) {
                // if special character found then add 1 to
                // the c
                c++;
            }
        }

        // if c value is greater than 0 then print no
        // means special character is found in string
        if (c > 0) {
            Console.WriteLine("string is not accepted");
        }
        else {
            Console.WriteLine("string is accepted");
        }
    }
}
JavaScript
// JavaScript code
// to check if any special character is present
// in a given string or not
const n = "Geeks$For$Geeks";
let c = 0;
const s = "[@_!#$%^&*()<>?}{~:]"; // special character set

for (let i = 0; i < n.length; i++) {
    // checking if any special character is present in given string or not
    if (s.includes(n[i])) {
        // if special character found then add 1 to the c
        c++;
    }
}

// if c value is greater than 0 then print no
// means special character is found in string
if (c) {
    console.log("string is not accepted");
} else {
    console.log("string is accepted");
}

Output
string is not accepted

Using inbuilt methods:

Here is another approach to checking if a string contains any special characters without using regular expressions:

C++
#include <iostream>
#include <string>

using namespace std;

bool hasSpecialChar(string s)
{
    for (char c : s) {
        if (!(isalpha(c) || isdigit(c) || c == ' ')) {
            return true;
        }
    }
    return false;
}

int main()
{
    string s = "Hello World";
    if (hasSpecialChar(s)) {
        cout << "The string contains special characters."
             << endl;
    }
    else {
        cout << "The string does not contain special "
                "characters."
             << endl;
    }

    s = "Hello@World";
    if (hasSpecialChar(s)) {
        cout << "The string contains special characters."
             << endl;
    }
    else {
        cout << "The string does not contain special "
                "characters."
             << endl;
    }

    return 0;
}
Java
class Main {
    public static boolean hasSpecialChar(String s)
    {
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (!(Character.isLetterOrDigit(c)
                  || c == ' ')) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args)
    {
        String s1 = "Hello World";
        if (hasSpecialChar(s1)) {
            System.out.println(
                "The string contains special characters.");
        }
        else {
            System.out.println(
                "The string does not contain special characters.");
        }
        String s2 = "Hello@World";
        if (hasSpecialChar(s2)) {
            System.out.println(
                "The string contains special characters.");
        }
        else {
            System.out.println(
                "The string does not contain special characters.");
        }
    }
}
Python3
def has_special_char(s):
    for c in s:
        if not (c.isalpha() or c.isdigit() or c == ' '):
            return True
    return False


# Test the function
s = "Hello World"
if has_special_char(s):
    print("The string contains special characters.")
else:
    print("The string does not contain special characters.")

s = "Hello@World"
if has_special_char(s):
    print("The string contains special characters.")
else:
    print("The string does not contain special characters.")
# This code is contributed by Edula Vinay Kumar Reddy
C#
using System;

class GFG {
    // This method checks if a string contains any special
    // characters.
    public static bool HasSpecialChar(string s)
    {
        // Iterate over each character in the string.
        for (int i = 0; i < s.Length; i++) {
            char c = s[i];
            // If the character is not a letter, digit, or
            // space, it is a special character.
            if (!(char.IsLetterOrDigit(c) || c == ' ')) {
                return true;
            }
        }
        // If no special characters were found, return
        // false.
        return false;
    }

    static void Main(string[] args)
    {
        string s1 = "Hello World";
        // Check if s1 contains any special characters and
        // print the result.
        if (HasSpecialChar(s1)) {
            Console.WriteLine(
                "The string contains special characters.");
        }
        else {
            Console.WriteLine(
                "The string does not contain special characters.");
        }
        string s2 = "Hello@World";
        // Check if s2 contains any special characters and
        // print the result.
        if (HasSpecialChar(s2)) {
            Console.WriteLine(
                "The string contains special characters.");
        }
        else {
            Console.WriteLine(
                "The string does not contain special characters.");
        }
    }
}
JavaScript
function hasSpecialChar(s) {
    for (let i = 0; i < s.length; i++) {
        const c = s.charAt(i);
        if (!(c.match(/^[a-zA-Z0-9 ]+$/))) {
            return true;
        }
    }
    return false;
}

let s = "Hello World";
if (hasSpecialChar(s)) {
    console.log("The string contains special characters.");
} else {
    console.log("The string does not contain special characters.");
}

s = "Hello@World";
if (hasSpecialChar(s)) {
    console.log("The string contains special characters.");
} else {
    console.log("The string does not contain special characters.");
}

Output
The string does not contain special characters.
The string contains special characters.

This approach uses the isalpha() and isdigit() methods to check if a character is an alphabetical character or a digit, respectively. If a character is neither an alphabetical character nor a digit, it is considered a special character.

The time complexity of this function is O(n), where n is the length of the input string, because it involves a single loop that iterates through all the characters in the string.

The space complexity of this function is O(1), because it does not use any additional data structures and the space it uses is independent of the input size.

Approach#4:using string.punctuation

Algorithm

1. Import the string module in Python, which contains a string called punctuation that includes all special characters.
2. Iterate through each character in the string.
3. Check if the character is in the punctuation string.
4. If a special character is found, print “String is not accepted”. Otherwise, print “String is accepted”.

Python3
import string

def check_string(s):
    for c in s:
        if c in string.punctuation:
            print("String is not accepted")
            return
    print("String is accepted")

# Example usage
check_string("Geeks$For$Geeks")  # Output: String is not accepted
check_string("Geeks For Geeks")  # Output: String is accepted

Output
String is not accepted
String is accepted

Time complexity: O(n), where n is the length of the input string. The loop iterates over each character in the string once.
Space complexity: O(1), as we are using only the string.punctuation string from the string module, which has a constant length.

METHOD 5:Using ASCII values

APPROACH:

The check_special_char_ascii function uses ASCII values to check if the input string contains any special characters. It iterates through each character in the string and checks if its ASCII value falls outside the range of alphabets and digits. If a special character is found, the function returns “String is not accepted.” Otherwise, it returns “String is accepted.”

ALGORITHM:

1. Initialize a for loop that iterates through each character in the input string.
2. For each character, check its ASCII value using the ord() function.
3. If the ASCII value falls outside the range of alphabets and digits, return “String is not accepted”.
4. If the loop completes without finding any special characters, return “String is accepted”.

C++
#include <iostream>
#include <string>

bool checkSpecialCharASCII(const std::string& str) {
    for (char c : str) {
        if (c < 48 || (c > 57 && c < 65) || (c > 90 && c < 97) || c > 122) {
            return false;
        }
    }
    return true;
}

int main() {
    std::string str = "Geeks$For$Geeks";
    if (checkSpecialCharASCII(str)) {
        std::cout << "String is accepted." << std::endl;
    } else {
        std::cout << "String is not accepted." << std::endl;
    }
    return 0;
}
Java
public class Main {
    // Function to check if a string contains only alphanumeric characters
    static boolean checkSpecialCharASCII(String str) {
        // Iterate through each character in the string
        for (char c : str.toCharArray()) {
            // Check if the character is not an alphanumeric character based on ASCII values
            if (!(c >= '0' && c <= '9') && !(c >= 'A' && c <= 'Z') && !(c >= 'a' && c <= 'z')) {
                return false; // If not alphanumeric, return false
            }
        }
        return true; // If all characters are alphanumeric, return true
    }

    public static void main(String[] args) {
        String str = "Geeks$For$Geeks";
        // Check if the string contains only alphanumeric characters
        if (checkSpecialCharASCII(str)) {
            System.out.println("String is accepted."); // Print if accepted
        } else {
            System.out.println("String is not accepted."); // Print if not accepted
        }
    }
}
//This code is contributed by Adarsh.
Python3
def check_special_char_ascii(string):
    for char in string:
        if ord(char) < 48 or (57 < ord(char) < 65) or (90 < ord(char) < 97) or ord(char) > 122:
            return "String is not accepted."
    return "String is accepted."

# Example Usage
string = "Geeks$For$Geeks"
print(check_special_char_ascii(string))
C#
using System;

class Program
{
    static string CheckSpecialCharASCII(string input)
    {
        // Loop through each character in the input string
        foreach (char c in input)
        {
            // Check if the ASCII value of the character is less than 48 or greater than 122
            if (c < 48 || (c > 57 && c < 65) || (c > 90 && c < 97) || c > 122)
            {
                return "String is not accepted.";
            }
        }
        
        // If no special characters were found, return "String is accepted."
        return "String is accepted.";
    }

    static void Main(string[] args)
    {
        string input = "Geeks$For$Geeks";
        Console.WriteLine(CheckSpecialCharASCII(input));
    }
}
JavaScript
// Function to check if a string contains only alphanumeric characters
function checkSpecialCharASCII(str) {
    // Iterate through each character in the string
    for (let i = 0; i < str.length; i++) {
        const c = str.charAt(i);
        // Check if the character is not an alphanumeric character based on ASCII values
        if (!(c >= '0' && c <= '9') && !(c >= 'A' && c <= 'Z') && !(c >= 'a' && c <= 'z')) {
            return false; // If not alphanumeric, return false
        }
    }
    return true; // If all characters are alphanumeric, return true
}

// Main function
function main() {
    const str = "Geeks$For$Geeks";
    // Check if the string contains only alphanumeric characters
    if (checkSpecialCharASCII(str)) {
        console.log("String is accepted."); // Print if accepted
    } else {
        console.log("String is not accepted."); // Print if not accepted
    }
}

// Call the main function
main();

Output
String is not accepted.

Time Complexity: The function iterates through each character in the string once, so the time complexity is O(n), where n is the length of the string.

Space Complexity: The function uses constant space, as it only creates a few variables to store the input string and the ASCII values of the characters. Therefore, the space complexity is O(1).



Similar Reads

Python - Test if String contains any Uppercase character
Given a String, Test if it contains any uppercase character. Input : test_str = 'geeksforgeeks' Output : False Explanation : No uppercase character in String.Input : test_str = 'geeksforgEeks' Output : True Explanation : E is uppercase in String. Method #1 : Using loop + isupper() In this, we iterate for each character in String, check for uppercas
6 min read
Python - Check if string contains any number
In this article, we will check How to check if a string contains a number in Python, we are given a string and we have to return a Boolean result i.e. True or False stating whether a digit is present in the string or not. Example Input: Test_str = 'Geeks42eeks' Output: True Input: Test_str = 'GeeksForGeeks' Output: FalseExplanation: In this, we are
5 min read
Python program to Count Uppercase, Lowercase, special character and numeric values using Regex
Prerequisites: Regular Expression in Python Given a string. The task is to count the number of Uppercase, Lowercase, special character and numeric values present in the string using Regular expression in Python. Examples: Input : "ThisIsGeeksforGeeks!, 123" Output :No. of uppercase characters = 4No. of lowercase characters = 15No. of numerical char
2 min read
Python program to read character by character from a file
Python is a great language for file handling, and it provides built-in functions to make reading files easy with which we can read file character by character. In this article, we will cover a few examples of it. Example Input: GeeksOutput: G e e k sExplanation: Iterated through character by character from the input as shown in the output.Read a fi
2 min read
Python | Check whether string contains only numbers or not
Given a string, write a Python program to find whether a string contains only numbers or not. Let's see a few methods to solve the above task. Check if String Contains Only Numbers Check if String Contains Only Numbers using isdigit() method Python String isdigit() method returns “True” if all characters in the string are digits, Otherwise, It retu
4 min read
Python | Ways to check if given string contains only letter
Given a string, write a Python program to find whether a string contains only letters and no other keywords. Let's discuss a few methods to complete the task. Method #1: Using isalpha() method C/C++ Code # Python code to demonstrate # to find whether string contains # only letters # Initialising string ini_str = "ababababa" # Printing ini
3 min read
Check if String Contains Substring in Python
This article will cover how to check if a Python string contains another string or a substring in Python. Given two strings, check whether a substring is in the given string. Input: Substring = "geeks" String="geeks for geeks"Output: yesInput: Substring = "geek" String="geeks for geeks"Output: yesExplanation: In this, we are checking if the substri
8 min read
Python | Check if string ends with any string in given list
While working with strings, their prefixes and suffix play an important role in making any decision. For data manipulation tasks, we may need to sometimes, check if a string ends with any of the matching strings. Let's discuss certain ways in which this task can be performed. Method #1 : Using filter() + endswith() The combination of the above func
6 min read
Python program to check if the list contains three consecutive common numbers in Python
Our task is to print the element which occurs 3 consecutive times in a Python list. Example : Input : [4, 5, 5, 5, 3, 8] Output : 5 Input : [1, 1, 1, 64, 23, 64, 22, 22, 22] Output : 1, 22 Approach : Create a list.Create a loop for range size – 2.Check if the element is equal to the next element.Again check if the next element is equal to the next
3 min read
Remove Special Characters from String Python
The generic problem faced by the programmers is to remove unwanted characters from a string using Python. But sometimes the requirement is way above and demands the removal of more than 1 character, but a list of such malicious characters. These can be in the form of special characters for reconstructing valid passwords and many other applications
6 min read
Python program to verify that a string only contains letters, numbers, underscores and dashes
Given a string, we have to find whether the string contains any letters, numbers, underscores, and dashes or not. It is usually used for verifying username and password validity. For example, the user has a string for the username of a person and the user doesn't want the username to have any special characters such as @, $, etc. Prerequisite: Regu
4 min read
Python - Create a Dictionary with Key as First Character and Value as Words Starting with that Character
In this article, we will code a python program to create a dictionary with the key as the first character and value as words starting with that character. Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only a single value as an element, Dictionary holds t
6 min read
Python | Insert character after every character pair
Sometimes, we can have a problem in which we need to insert a specific character after a pair(second) characters using Python. This kind of problem can occur while working with data, that require insertion of commas or any other special character mainly in the Machine Learning domain. Let's discuss certain ways in which this problem can be solved.
6 min read
Python | Remove tuple from list of tuples if not containing any character
Given a list of tuples, the task is to remove all those tuples which do not contain any character value. Example: Input: [(', ', 12), ('...', 55), ('-Geek', 115), ('Geeksfor', 115),] Output: [('-Geek', 115), ('Geeksfor', 115)] Method #1 : Using list comprehension C/C++ Code # Python code to remove all those # elements from list of tuple # which doe
4 min read
Python - Remove strings with any non-required character
Given a Strings list, remove string, if it contains any unwanted character. Input : test_list = ["gfg", "is", "best", "for", "geeks"], chr_list = ['f', 'm', 'n', 'i'] Output : ['best', 'geeks'] Explanation : Given Strings don't contain f, m, n or i. Input : test_list = ["gfg", "is", "best", "for", "geeks"], chr_list = ['f', 'm', 'n'] Output : ['bes
6 min read
PyQt5 - Selecting any one check box among group of check boxes
When we make a form and there are multiple check boxes. We can select some of them or only one of them as they are contradictory to each other. So the GUI (Graphical User Interface) stops us to selecting more than one check box, if we select more than one check box it makes other boxes unchecked. In this article we will see how to make a group of c
3 min read
Python | Check order of character in string using OrderedDict( )
Given an input string and a pattern, check if characters in the input string follows the same order as determined by characters present in the pattern. Assume there won’t be any duplicate characters in the pattern. Examples: Input: string = "engineers rock"pattern = "er";Output: trueExplanation: All 'e' in the input string are before all 'r'.Input:
3 min read
Python - Check whether a string starts and ends with the same character or not (using Regular Expression)
Given a string. The task is to write a regular expression to check whether a string starts and ends with the same character. Examples: Input : abbaOutput : ValidInput : aOutput : ValidInput : abcOutput : InvalidSolution: The input can be divide into 2 cases: Single character string: All single character strings satisfies the condition that they sta
2 min read
Check whether the Average Character of the String is present or not
Given a string of alphanumeric characters, the task is to check whether the average character of the string is present or not. Average character refers to the character corresponding to the ASCII value which is the floor of the average value of the ASCII values of all characters in the string. Examples: Input: abcdefOutput: d YesExplanation: string
7 min read
Python | Check if list contains consecutive numbers
Given a list of numbers, write a Python program to check if the list contains consecutive integers. Examples: Input : [2, 3, 1, 4, 5] Output : True Input : [1, 2, 3, 5, 6] Output : False Let's discuss the few ways we can do this task. Approach #1 : using sorted() This approach uses sorted() function of Python. We compare the sorted list with list o
3 min read
Check if directory contains files using python
Finding if a directory is empty or not in Python can be achieved using the listdir() method of the os library. OS module in Python provides functions for interacting with the operating system. This module provides a portable way of using operating system dependent functionality. Syntax: os.listdir(<directory path>) Returns: A list of files pr
3 min read
Python - Check if Tuple contains only K elements
Sometimes, while working with Python tuples, we can have a problem in which we need to test if any tuple contains elements from set K elements. This kind of problem is quite common and have application in many domains such as web development and day-day programming. Let's discuss certain ways in which this task can be done. Input : test_tuple = (1,
3 min read
Check whether a Numpy array contains a specified row
In this article we will learn about checking a specified row is in NumPy array or not. If the given list is present in a NumPy array as a row then the output is True else False. The list is present in a NumPy array means any row of that numpy array matches with the given list with all elements in given order. This can be done by using simple approa
2 min read
Check if given number contains only “01” and “10” as substring in its binary representation
Given a number N, the task is to check if the binary representation of the number N has only "01" and "10" as a substring or not. If found to be true, then print "Yes". Otherwise, print "No".Examples: Input: N = 5 Output: Yes Explanation: (5)10 is (101)2 which contains only "01" and "10" as substring.Input: N = 11 Output: No Explanation: (11)10 is
6 min read
Check if dataframe contains infinity in Python - Pandas
Prerequisites: Pandas There are various cases where a data frame can contain infinity as value. This article discusses how we can keep track of infinities in our data frame. ApproachImport moduleCreate a data frame, for this article, it is done using a dictionary. For including infinity in the data, import NumPy module, and use np.inf for positive
2 min read
Python Check if the List Contains Elements of another List
In Python programming, there can be a case where we have to check whether a list contains elements of Another List or not. In that case, we can follow several approaches for doing so. In this article, we will be discussing several approaches to check whether a list contains elements of another list or not. Python List Contains Elements of another L
2 min read
Python | Check if list contains all unique elements
Some list operations require us to check if all the elements in the list are unique. This usually happens when we try to perform the set operations in a list. Hence this particular utility is essential at these times. Let's discuss certain methods by which this can be performed. Method #1: Naive Method Solutions usually start from the simplest meth
8 min read
How to check if a set contains an element in Python?
In this article, we will discuss how to check if a set contains an element in a. Example This example uses the in operator to check if the number 3 is present in the set my_set. [GFGTABS] Python # Create a set my_set = {1, 2, 3, 4, 5} # Check if an element is in the set if 3 in my_set: print("Element found in the set") else: print("E
2 min read
Python | Check if suffix matches with any string in given list
Given a list of strings, the task is to check whether the suffix matches any string in the given list. Examples: Input: lst = ["Paras", "Geeksforgeeks", "Game"], str = 'Geeks' Output: TrueInput: lst = ["Geeks", "for", "forgeeks"], str = 'John' Output: False Let's discuss a few methods to do the task. Method #1: Using any() The most concise and read
6 min read
Python | Check if any String is empty in list
Sometimes, while working with Python, we can have a problem in which we need to check for perfection of data in list. One of parameter can be that each element in list is non-empty. Let's discuss if a list is perfect on this factor using certain methods. Method #1 : Using any() + len() The combination of above functions can be used to perform this
6 min read