OneBite.Dev - Coding blog in a bite size

check if a string contains only letters in python

Code snippet on how to check if a string contains only letters in python

def only_letters(string):
  for char in string:
    if not char.isalpha():
      return False
  return True

The above code checks if a given string contains only letters. It works by looping through each character in the string, and then applying .isalpha() to each character to check if it’s an alphabetic character. If any of the characters are not alphabetic, the code will return False. Otherwise, if all the characters are alphabetic, the code will return True. This function can be used to ensure that the data given to us is only comprised of letters.

python