-4

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.

Gab
  • 5,604
  • 6
  • 36
  • 52
Kelly Edwards
  • 19
  • 1
  • 4
  • 2
    what 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 Answers4

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
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
Community
  • 1
  • 1
Gab
  • 5,604
  • 6
  • 36
  • 52
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
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]':