I've created an alphabet checker that is similar to str.isAlpha()
.
I know that python has its built-in function.
str.isalpha()
Return true if all characters in the string are alphabetic and there is at least one character, false otherwise. Alphabetic characters are those characters defined in the Unicode character database as "Letter", i.e., those with general category property being one of "Lm", "Lt", "Lu", "Ll", or "Lo". Note that this is different from the "Alphabetic" property defined in the Unicode Standard.
I put my implementation code here: https://gist.github.com/anonymous/7833d25fc450e69ee323bfc39bdd0da5
I included my code snippet below:
import string
# Hint: Use these string constants to ignore capitalization and/or punctuation
string.ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
string.ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.ascii_letters = string.ascii_lowercase + string.ascii_uppercase
def ascii_letters(text):
#This m ethod will return True if the string
# is an uppercase or lowercase letter from A to Z.
# If the string contains any non-letter characters, then it will return False.
for index in text:
if index in string.ascii_letters:
return True
else:
return False
return None
1 Answer 1
In this answer I am assuming that high performance is not needed
In general that approach is okay but I do not think that code is fulfilling the requirements. For example
ascii_letters("A2") == True
ascii_letters("") == None
I propose following steps:
Fix your algorithm (some unit tests would be great!)
Think about if is this really necessary to check whether the letter is in set of containing both lower and upper case letters.
Next, think about iteration over whole string: is this needed? There are functions in python which can check logical condition on whole list.
Why do you need to include
string
? There is no need to override already existing variables.Try to do pythonic one liner using all points above.
Explore related questions
See similar questions with these tags.