Is there a specific function that returns true if characters in the string are special characters (ex: #. @. $)? Like, the isalpha() function returns true if all the characters in a string are letters.
I have to create a program where I need to ask a user for a string and then my program must print the length of the string, the number of letters, the number of digits and the number of characters that are not letters.
counter = 0
num = 0
extra = 0
wrd = raw_input("Please enter a short sentence.")
for i in wrd:
if i.isalpha():
counter = counter + 1
print "You have " + str(counter) +" letters in your sentence."
for n in wrd:
if n.isnumeric():
num = num + 1
print "You have " + str(num) + " number(s) in your sentence"
for l in wrd:
extra = extra + 1
print "You have " + str(extra) + " characters that are not letters or numbers."
I got the first two parts figured out albeit I'm stuck on the last...I know its easier to just create one while loop but since I already started, I want to stick with three four loops.
4 Answers 4
You don't need another function. Since you've already counted the other characters, subtract them from the total:
print "You have", len(wrd) - counter - num, "characters that are not letters or numbers."
Comments
Is there a specific function that returns true if characters in the string are special characters (ex: #. @. $)? Like, the isalpha() function returns true if all the characters in a string are letters.
No, but its pretty easy to create your own:
import string
def has_special_chars(s):
return any(c in s for c in string.punctuation)
Test:
>>> has_special_chars("ab@tjhjf$dujhf&")
True
>>> has_special_chars("abtjhjfdujhf")
False
>>>
In your case, you would use it like:
for l in wrd:
if has_special_chars(l)
extra=extra+1
But as @TigerHawkT3 has already beat me to saying, you should simply use len(wrd) - counter - num instead. Its the most canonical and obvious way.
Comments
Just to log a generic answer that will apply beyond this context -
import string
def num_special_char(word):
count=0
for i in word:
if i in string.punctuation:
count+=1
return count
print "You have " + str(num_special_char('Vi$vek!')) + " characters that are not letters or numbers."
Output
You have 2 characters that are not letters or numbers.
Comments
Use one for loop with if, elif and else:
sentence = raw_input("Please enter a short sentence.")
alpha = num = extra = 0
for character in sentence:
if character.isspace():
pass
elif character.isalpha():
alpha += 1
elif character.isnumeric():
num += 1
else:
extra += 1
print "You have {} letters in your sentence.".format(alpha)
print "You have {} number(s) in your sentence".format(num)
print "You have {} characters that are not letters or numbers.".format(extra)
len(wrd) - counter - num?