0

im trying to make sure no letter characters are in the answer the user enters and this is the solution i have right now (i know it is terribly inefficient) is there a way to check for all letter characters in one if statement?

    if "a" in ans or "b" in ans or "c" in ans or "d" in ans or "e" in ans or "f" in ans or "g" in ans or "h" in ans:
    error()
elif "i" in ans or "j" in ans or "k" in ans or "l" in ans or "m" in ans or "n" in ans or "o" in ans or "p" in ans:
    error()
elif "q" in ans or "r" in ans or "s" in ans or "t" in ans or "u" in ans or "v" in ans or "w" in ans or "x" in ans:
    error()
elif "y" in ans or "z" in ans:
    error()
else:

3 Answers3

4

You can achieve this using regex

import re
ans = input("String to test : ")

if re.search(r"[a-zA-Z]", ans) == None: # Test for lowercase and uppercase letters
    print("No letter in this string")
else:
    print("Letter found")

However this will not be triggered by é è ù ì etc.

Marius ROBERT
  • 426
  • 4
  • 15
0
from string import ascii_letters

ans = input()

for ch in ascii_letters:
    if ch in ans:
        print("Error")
        break
else:
    print("No Error")
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Aman Burnwal
  • 11
  • 1
  • 2
  • This is not very efficient as it will loop the whole string for every letter. A small improvement would be to at least only use lowercase letters by doing ans = input().lower()` and `for ch in ascii_lowercase` – Tomerikoo May 31 '22 at 09:59
  • The whole loop can also be compacted into an `any` call: `if any(ch in ans for ch in ascii_lowercase): print("Error")` – Tomerikoo May 31 '22 at 10:10
  • @Tomerikoo, yes .lower() will be a better solution. Thanks for better code. – Aman Burnwal May 31 '22 at 10:43
  • Kindly add a line or two to explain what you are doing. This will help the readers to understand the answer more clearly. – Abhyuday Vaish May 31 '22 at 13:59
-3

You can use string.ascii_letters to get all letters, from lowercase to uppercase. To only get lowercase letter, use string.ascii_lowercase.

Edit: To further validate input as a single letter, I would say use assert.

Example:

from string import ascii_letters

input_var = input()

assert len(input_var) == 1, "Input must only contain 1 character."

if input_var in ascii_letters:
    print("input is a letter")
else:
    print("input is not a letter")
  • That is the opposite of the question. The input is not restricted to one character and the OP wants to make sure there are ***no*** letters in the input... – Tomerikoo May 31 '22 at 09:48