Assume that x
is a string variable that has been given a value. Write an expression whose value is true
if and only if x
is NOT a letter.
Asked
Active
Viewed 5,702 times
-4

Gab
- 5,604
- 6
- 36
- 52

Kelly Edwards
- 19
- 1
- 4
-
2what does your attempt look like? – ergonaut Oct 08 '15 at 00:30
-
I tried notx.true() recently and it says Remarks: ⇒ Unexpected identifiers: notx, true More Hints: ⇒ You almost certainly should be using: not ⇒ You almost certainly should be using: x – Kelly Edwards Oct 08 '15 at 00:32
-
`x != 'a'` tests if `x` is not a. `x != 'a' and x != 'b'` tests if it is neither 'a' nor 'b' ... This should be your first attempt. Then you learn about the `in` operator and/or comparisons. Then you might deviate from the right path and learn regular expressions. – Kijewski Oct 08 '15 at 00:50
4 Answers
3
def isLetter(ch):
import string
return len(ch) == 1 and ch in string.ascii_letters
print(isLetter('A'))
True

LetzerWille
- 5,355
- 4
- 23
- 26
-
*Write an expression whose value is true if and only if x is NOT a letter*, this is the most roundabout way possible to do that. – Padraic Cunningham Oct 08 '15 at 22:53
2
If you want to check the type of the variable x
, you can use the following:
if type(x) is str:
print 'is a string'
In python, String and Char will have the same type and same output unlike languages like java.
type(chr(65)) == str
type('A') == str
EDIT:
As @Kay suggested, you should use isinstance(foo, Bar)
instead of type(foo) is bar
since isinstance is checking for inheritance while type does not.
See this for more details about isinstance
vs type
Using isinstance will also support unicode strings.
isinstance(u"A", basestring)
>>> true
# Here is an example of why isinstance is better than type
type(u"A") is str
>>> false
type(u"A") is basestring
>>> false
type(u"A") is unicode
>>> true
EDIT 2:
Using regex to validate ONLY ONE letter
import re
re.match("^[a-zA-Z]$", "a") is not None
>>> True
re.match("^[a-zA-Z]$", "0") is not None
>>> False
2
Turns out the answer to it is not((x>='A' and x<='Z') or (x>='a' and x<='z'))

Padraic Cunningham
- 176,452
- 29
- 245
- 321

Kelly Edwards
- 19
- 1
- 4
-
Actually Python allows you to write comparisons like a mathematical notation: `a < b < c` <-> `a < b and b < c`, but `a`, `b` and `c` are only evaluated once. – Kijewski Oct 08 '15 at 01:02
-
-
No need to overly complicate it `return not x.isalpha()`, it if it is not alphabetic it cannot be a letter – Padraic Cunningham Oct 08 '15 at 22:52
0
Use regular expression. http://www.pythex.org is a good learning spot, official docs here: https://docs.python.org/2/library/re.html
something like this should work though:
if x != '[a-zA-Z]':

Ryan Holleran
- 11
- 1