Symbol-only string detection

15,067

Symbols is a little vague but here is a strategy:

symbols = input("Enter symbol string:")
valid_symbols = "!@#$%^&*()_-+={}[]"

has_only_symbols = True

for ch in symbols:
    if ch not in symbols:
        has_only_symbols = False
        break

if has_only_symbols:
    print('Input only had symbols')
else:
    print('Input had something other than just symbols')

The above code first creates a list of symbols which you want to ensure the string is created out of called valid_symbols. Next it creates a variable called has_only_symbols that holds a value of True to begin with. Next it begins to check that each character in the input string exists in valid_symbols. If it hits a character which is invalid then it changes the value of has_only_symbols to False and breaks out of the for loop (no need to check the rest of the string). After the loop is done it checks whether has_only_symbols is True or False and does something accordingly.

Also as a side not, some of your code is not doing what you think it is:

if symbols == symbols.isalpha():
    ...

will test if symbols, your input string, is equal to the result of symbols.isalpha() which returns a boolean True or False. What you probably meant is just:

if symbols.isalpha():
    ...

The elif statement is strange as well. You have begun referencing some variable called a but you do not have it defined anywhere in the code you posted. From your description and code it seems you meant to have this elif statement also reference symbols and call the isdigit method:

if symbols.isalpha():
    ...
elif symbols.isdigit():
    ...
else:
    ...

However this is not logically complete as a string with mixed letter, digit, and symbol will slip through. For example abc123!@# will fail both the tests and get printed. You want something more exclusive like the above code I have written.

Share:
15,067
Chrysoula Kaloumenou
Author by

Chrysoula Kaloumenou

Updated on June 26, 2022

Comments

  • Chrysoula Kaloumenou
    Chrysoula Kaloumenou almost 2 years

    I'm fairly new to Python (and programming in general), so I often end up facing really silly issues, such as the one below.

    What I want is to repeatedly check if all the characters in a user input are symbols. When such an input is entered, I want to print that string.

    Since there doesn't seem to be a way to specifically test for symbols, I decided to test for letters first, and then for numbers, and if both of them come up as negative, then it should print the text.

    Here is my code:

    while True:
    
      symbols = input("Enter symbol string:")
    
      if symbols == symbols.isalpha():
        print (symbols.isalpha())
      elif not a == a.isalpha():
        print (a.isalpha())
        break
    
  • Magda
    Magda over 3 years
    Don't you have to initialize count as 0 outside of the loop?