Game Development Reference
In-Depth Information
lowercase letter from A to Z. If the string contains any non-letter characters, then
isalpha()
will return
False
. Try typing the following into the interactive shell:
>>> 'Hello'.isalpha()
True
>>> 'Forty two'.isalpha()
False
>>> 'Fortytwo'.isalpha()
True
>>> '42'.isalpha()
False
>>> ''.isalpha()
False
>>>
As you can see,
'Forty two'.isalpha()
will return
False
because
'Forty
two'
has a space in it, which is a non-letter character.
'Fortytwo'.isalpha()
returns
True
because it does not have this space.
'42'.isalpha()
returns
False
because both
'4'
and
'2'
are non-letter characters. And
''.isalpha()
is
False
because
isalpha()
only returns
True
if the string has only letter characters and is not
blank.
We will use the
isalpha()
method in our program next.
31. for symbol in message:
32. if symbol.isalpha():
33. num = ord(symbol)
34. num += key
We will run a
for
loop over each letter (remember in cryptography they are called
symbols) in the
message
string. Strings are treated just like lists of single-character
strings. If
message
had the string
'Hello'
, then
for symbol in 'Hello'
would
be the same as
for symbol in ['H', 'e', 'l', 'l', 'o']
. On each
iteration through this loop,
symbol
will have the value of a letter in
message
.
The reason we have the
if
statement on line 32 is because we will only encrypt/decrypt
letters in the message. Numbers, signs, punctuation marks, and everything else will stay in
their untranslated form. The
num
variable will hold the integer ordinal value of the letter
stored in
symbol
. Line 34 then "shifts" the value in
num
by the value in
key
.
The
isupper()
and
islower()
String Methods
The
isupper()
and
islower()
string methods (which are on line 36 and 41) work