[Tutor] removing digits from a file

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Fri, 18 May 2001 15:43:42 -0700 (PDT)


On Fri, 18 May 2001, sheri wrote:

> i want to do something like this 
>   
> if char (is a digit)
>    delete char

To do this, we can write a small "isDigit()" function that tells us if a
character is a digit.

###
def isDigit(mychar):
    return mychar == '0' or mychar == '1' or mychar == '2' or ...
###

But we can see that this is a really dull way of writing this.  An easier
way to do this is to take advantage of a list structure: doing this will
allow us to say: "Go though each one of these digits, and see if it
matches with mychar."

###
def isDigit(mychar):
    numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    for n in numbers:
        if n == mychar: return 1
    return 0
###

We're being careful to put those numbers in quotes, because we want to
make sure we're making comparisons between two characters.  Python's a
little strict about this:

###
>>> 1 == '1'
0
###

so we need to be aware of the trap of comparing between apples and
oranges.



This version of isDigit() works, but there are small idioms we can use to
make this even nicer.

One idiom is to use the 'in' operation on our list of numbers.  We can say
that if our mychar is 'in' the numbers, we're ok:

###
def isDigit(mychar):
    numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    return mychar in numbers
###


One other cute trick we can use is to express the characters from '0' to
'9' like this:


###
def isDigit(mychar):
    numbers = map(str, range(10))
    return mychar in numbers
###

which means: "Let's allows numbers to stand for the list that contains the
range from 0 through 9.  By the way, we're making all those digits into
strings first."