If you look at the sample solutions to the exercises for Week 2 you will notice a few things that you have not met so far. In the post below, which discusses one aspect of the ‘raw_input()’ function, a method for converting numbers held as strings into their actual number value is demonstrated. This works fine if the contents of the string given to the ‘int()’ function are digits e.g. “24” however if the string contains letters e.g. “john” then the function fails. This is a common dilemma in programming – you need to ensure that the type of data you are using is the correct (expected) data type before you use it.
The ‘wk2_ex1_age.py’ program shows one way that you can check what type of data is in a string before you use, namely to use ‘str.isdigit()’, one of a family of functions that work with strings:
isalnum(), isalpha(), isdigit(), islower(), isupper(), isspace(), and istitle()
The length of the string being compared must be at least 1, or the is* methods will return False. In other words, a string object of len(string) == 0, is considered “empty”, or False.
- isalnum returns True if the string is entirely composed of alphabetic or numeric characters (i.e. no punctuation).
- isalpha and isdigit work similarly for alphabetic characters or numeric characters only.
- isspace returns True if the string is composed entirely of whitespace.
- islower, isupper, and istitle return True if the string is in lowercase, uppercase, or titlecase respectively. Uncased characters are “allowed”, such as digits, but there must be at least one cased character in the string object in order to return True. Titlecase means the first cased character of each word is uppercase, and any immediately following cased characters are lowercase. Curiously, ‘Y2K’.istitle() returns True. That is because uppercase characters can only follow uncased characters. Likewise, lowercase characters can only follow uppercase characters. Hint: whitespace is uncased.
see http://en.wikibooks.org/wiki/Python_Programming/Strings for other useful things to know about strings.