Hi!

I am teaching myself Python using John Zelle's excellent book Python Programming (ISBN: 1-887902-99-6). At the end of Chapter 4 - Computing with Strings is an exercise to convert an existing program to use a list to decode ASCII number input. My solution is shown below.

My problem is with the actual entry of the ASCII codes. My solution has a "if" test to remove the leading "0" from an input of say "033". With this test the output of the decode is correct in printing "!". Without the "if" test the output is "\x1b" at best or a run-time error for other numbers.

My question is this: is there a better way to convert raw input of say "033" to "33" than what I have used? Thanks in advance for any help.

My source code
---------------

import string

def main():
print "This script converts a sequence of ASCII numbers"
print "into the string of text that it represents."
print
data = getNumbers()
print data

def getNumbers():
# Setup an empty list
inString = []

# Get the numbers to decode
inNum = raw_input("Please enter an ASCII number\n(33 - 126, [Enter] to quit): ")
while inNum != "":
# strip leading '0's from ASCII numbers
if inNum[0] == "0":
inNum = inNum[1] + inNum[2]
inStr = chr(eval(inNum))
inString.append(inStr) # append the input to the list
inNum = raw_input("Please enter an ASCII number\n(33 - 126, [Enter] to quit): ")
return inString

if __name__ == '__main__':
main()


--
*Peter Anderson*
There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things—Niccolo Machiavelli, /The Prince/, ch. 6
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to