How do i check if a string contains only special characters in python?

So what I want to do is check if the string contains only special characters. An example should make it clear

Hello -> Valid
Hello?? -> Valid
?? -> Not Valid

Same thing done for all special characters including "."

How do i check if a string contains only special characters in python?

Bhargav Rao

47.3k27 gold badges122 silver badges137 bronze badges

asked Mar 4, 2015 at 17:02

1

You can use this regex with anchors to check if your input contains only non-word (special) characters:

^\W+$

If underscore also to be treated a special character then use:

^[\W_]+$

RegEx Demo

Code:

>>> def spec(s):
        if not re.match(r'^[_\W]+$', s):
            print('Valid')
        else:
            print('Invalid')


>>> spec('Hello')
Valid
>>> spec('Hello??')
Valid
>>> spec('??')
Invalid

answered Mar 4, 2015 at 17:03

anubhavaanubhava

732k62 gold badges533 silver badges612 bronze badges

16

You can use a costume python function :

>>> import string 
>>> def check(s):
...   return all(i in string.punctuation for i in s)

string.punctuation contain all special characters and you can use all function to check if all of the characters are special!

answered Mar 4, 2015 at 17:09

How do i check if a string contains only special characters in python?

MazdakMazdak

102k18 gold badges156 silver badges182 bronze badges

1

Here's the working code:

import string

def checkString(your_string):
    for let in your_string.lower():
        if let in string.ascii_lowercase:
            return True
    return False

answered Mar 4, 2015 at 17:18

How do i check if a string contains only special characters in python?

Texom512Texom512

4,6933 gold badges15 silver badges15 bronze badges

import string

s = input("Enter a string:")

if all(i in string.punctuation for i in s):
    print ("Only special characters")

else:
    print ("Valid")

use the above loop to set boolean events and use it accordingly

How do i check if a string contains only special characters in python?

SPYBUG96

1,0253 gold badges16 silver badges37 bronze badges

answered May 9, 2020 at 1:47

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Given string str of length N, the task is to check if the given string contains only special characters or not. If the string contains only special characters, then print “Yes”. Otherwise, print “No”.

    Examples:

    Input: str = “@#$&%!~”
    Output: Yes
    Explanation: 
    Given string contains only special characters. 
    Therefore, the output is Yes.

    Input: str = “Geeks4Geeks@#”
    Output: No
    Explanation: 
    Given string contains alphabets, number, and special characters. 
    Therefore, the output is No.

    Naive Approach: Iterate over the string and check if the string contains only special characters or not. Follow the steps below to solve the problem:

    • Traverse the string and for each character, check if its ASCII value lies in the ranges [32, 47], [58, 64], [91, 96] or [123, 126]. If found to be true, it is a special character.
    • Print Yes if all characters lie in one of the aforementioned ranges. Otherwise, print No.

    Time Complexity: O(N)
    Auxiliary Space: O(1)

    Space-Efficient Approach: The idea is to use Regular Expression to optimize the above approach. Follow the steps below:

    • Create the following regular expression to check if the given string contains only special characters or not.

    regex = “[^a-zA-Z0-9]+”

    where,

    • [^a-zA-Z0-9] represents only special characters.
    • +represents one or more times.
    • Match the given string with the Regular Expression using Pattern.matcher()in Java
    • Print Yes if the string matches with the given regular expression. Otherwise, print No.

    Below is the implementation of the above approach:

    C++

    #include <iostream>

    #include <regex>

    using namespace std;

    void onlySpecialCharacters(string str)

    {

      const regex pattern("[^a-zA-Z0-9]+");

      if (str.empty())

      {

         cout<< "No";

         return ;

      }

      if(regex_match(str, pattern))

      {

        cout<< "Yes";

      }

      else

      {

        cout<< "No";

      }

    }

    int main()

    {

      string str = "@#$&%!~";

      onlySpecialCharacters(str) ;

      return 0;

    }

    Java

    import java.util.regex.*;

    class GFG {

        public static void onlySpecialCharacters(

            String str)

        {

            String regex = "[^a-zA-Z0-9]+";

            Pattern p = Pattern.compile(regex);

            if (str == null) {

                System.out.println("No");

                return;

            }

            Matcher m = p.matcher(str);

            if (m.matches())

                System.out.println("Yes");

            else

                System.out.println("No");

        }

        public static void main(String args[])

        {

            String str = "@#$&%!~";

            onlySpecialCharacters(str);

        }

    }

    Python3

    import re

    def onlySpecialCharacters(Str):

        regex = "[^a-zA-Z0-9]+"

        p=re.compile(regex)

        if(len(Str) == 0):

            print("No")

            return

        if(re.search(p, Str)):

            print("Yes")

        else:

            print("No")

    Str = "@#$&%!~"

    onlySpecialCharacters(Str)

    C#

    using System;

    using System.Text.RegularExpressions; 

    class GFG{

    public static void onlySpecialchars(String str)

    {

      String regex = "[^a-zA-Z0-9]+";

      Regex rgex = new Regex(regex); 

      if (str == null)

      {

        Console.WriteLine("No");

        return;

      }

      MatchCollection matchedAuthors =

                      rgex.Matches(str);   

      if (matchedAuthors.Count != 0)

        Console.WriteLine("Yes");

      else

        Console.WriteLine("No");

    }

    public static void Main(String []args)

    {

      String str = "@#$&%!~";

      onlySpecialchars(str);

    }

    }

    Javascript

    <script>

          function onlySpecialchars(str)

          {

            var regex = /^[^a-zA-Z0-9]+$/;

            if (str.length < 1) {

              document.write("No");

              return;

            }

            var matchedAuthors = regex.test(str);

            if (matchedAuthors) document.write("Yes");

            else document.write("No");

          }

          var str = "@#$&%!~";

          onlySpecialchars(str);

     </script>

    Time Complexity: O(N)
    Auxiliary Space: O(1)


    How do you check if the string contains any special character in Python?

    Approach : Make a regular expression(regex) object of all the special characters that we don't want, then pass a string in search method. If any one character of string is matching with regex object then search method returns a match object otherwise return None.

    How do I check if a string contains special characters?

    To check if a string contains special characters, call the test() method on a regular expression that matches any special character. The test method will return true if the string contains at least 1 special character and false otherwise.

    How do you check if a string contains only numbers and special characters in Python?

    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 returns “False”.