[Tutor] string comparison
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Wed, 11 Jul 2001 15:11:15 -0700 (PDT)
On Wed, 11 Jul 2001, Paul Brown wrote:
> i am a very newbie to Python, and i am making my way through the Core
Hello!
> Python Programming book, and Exercise 6-5(b) says i have to determine if
> two strings match (without using the comparison operators or the cmp()
> built-in function) by scanning each string. Also, for extra credit, it
Do you mean checking each character in the string, letter by letter?
> asks me to add case-insensitivity to the solution. does anyone have any
> suggestions? i can only think to use the "==" operator. thanks
Whoa! That seems really restrictive to not allow '=='! Does the exercise
kebep us from doing '==' altogether, or just against two long strings?
(Wesley, I will buy your book today... *grin*)
I can think a convoluted way of getting around the restriction of not
using '=='. For example, if we're dealing with numbers, we can define
another notion of equality if we're devious and underhanded:
###
def numericEquals(x, y):
return not (x < y) and not (x > y)
###
That is, two numbers are equal only if one isn't larger than the other.
It's a mathematical statement, and extremely silly, but it does work:
###
>>> numericEquals(1, 1)
1
>>> numericEquals(1, 2)
0
>>> numericEquals(42, 42)
1
>>> numericEquals(42, 43)
0
###
Also, it turns out that we can treat single characters as numbers by using
the ord() "ordinal" function:
###
>>> ord('a')
97
>>> ord('z')
122
>>> ord('z') - ord('a')
25
###
By combining these two trains of thought, we can write a small function
that checks for string equality, without using the '==' equality
operation.
I really really doubt, however, that this is what the book had in mind...
*grin*
Good luck to you.