isalpha() if statement being ignored python - Stack Overflow
Using isalpha() within an IF statement
Python: Creating a len(string) and string.isalpha conditional - Stack Overflow
How can I check if character in a string is a letter? (Python) - Stack Overflow
Videos
Working on PSET2 - Readability wherein I have a function set up to count letters. I had this working previously by way of some backwards logic (I had it checking if each char was NOT a space or special char and only counting if true) and decided to redesign it to be more straight-forward. I'm now trying to use isalpha() to check each char, but I'm getting a return of 0 letter(s) every time.
int count_letts(string s)
{
int x = 0;
for(int i = 0, n = strlen(s); i < n; i++)
{
if(isalpha(s[i]) == true)
{
x++;
}
}
return x;
}I have a function for counting words that's almost identical to this using isblank() that works perfectly fine. I've read the man pages and notes from the lectures a couple times, Googled and searched this subreddit, but I don't see anyone with the same issue. What am I doing wrong?
Because the input string retains the \n character causing the input to fail:
Consider using userinput = raw_input("Please enter a word: ").strip() instead...
Also, isalpha() already checks if the length is one or more, reducing your code to:
if userinput.isalpha():
# whatever
And then your syntax error goes away quite nicely... (the extra ) after userinput)
The traceback you've pasted shows different code from your original snippet. You have an extra close bracket after len(userinput), which is the cause of the error.
You can use str.isalpha().
For example:
s = 'a123b'
for char in s:
print(char, char.isalpha())
Output:
a True
1 False
2 False
3 False
b True
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.
In python2.x:
>>> s = u'a1中文'
>>> for char in s: print char, char.isalpha()
...
a True
1 False
中 True
文 True
>>> s = 'a1中文'
>>> for char in s: print char, char.isalpha()
...
a True
1 False
� False
� False
� False
� False
� False
� False
>>>
In python3.x:
>>> s = 'a1中文'
>>> for char in s: print(char, char.isalpha())
...
a True
1 False
中 True
文 True
>>>
This code work:
>>> def is_alpha(word):
... try:
... return word.encode('ascii').isalpha()
... except:
... return False
...
>>> is_alpha('中国')
False
>>> is_alpha(u'中国')
False
>>>
>>> a = 'a'
>>> b = 'a'
>>> ord(a), ord(b)
(65345, 97)
>>> a.isalpha(), b.isalpha()
(True, True)
>>> is_alpha(a), is_alpha(b)
(False, True)
>>>