Reputation: 69
I want to check a character in the string if it's a number, space, upper/lower character or a special character ".'*^?..."
I came up with the solution that is not very slick, plus it can't check for special characters without adding extra lines in else statement.
def checker(str1):
if str1.isspace() is True:
print('it\'s a space')
if str1.isupper() is True:
print('it\'s a letter and it\'s upper')
if str1.islower() is True:
print('it\'s a letter and it\'s lower')
if str1.isdigit() is True:
print('it\'s a digit')
if str1.isascii() is True:
print('it\'s a special chracter')
string_letter = 'A'
checker(string_letter)
this code works... if I create some extra clause for special characters because right now it's just saying that space is a special character... it happens because .isascii()
just too broad for special characters.
Is there any native method that I miss that can do that functionality more elegantly? aka give information on a character in the string?
I am very new to python, so I'm sorry, maybe I was not able to find native solution because I am not very fluent in terminology yet.
Upvotes: 1
Views: 28
Reputation: 13551
Use elif
and place the special character checker to the last.
def checker(str1):
if str1.isspace():
print('it\'s a space')
elif str1.isupper():
print('it\'s a letter and it\'s upper')
elif str1.islower():
print('it\'s a letter and it\'s lower')
elif str1.isdigit():
print('it\'s a digit')
elif str1.isascii():
print('it\'s a special chracter')
string_letter = '&'
checker(string_letter)
Then,
it's a special chracter
Upvotes: 1