[Tutor] python string __add__
Bob Gailer
bgailer@alum.rpi.edu
Thu Jun 5 14:42:01 2003
At 11:00 AM 6/5/2003 -0700, tpc@csua.berkeley.edu wrote:
>I have a script that will take decimal numbers of any length as command
>line arguments and output the binary equivalent. However, I am trying to
>output one long string with no spaces. I attempted __add__ but got empty
>spaces. Is there a way for python string __add__ to output binary digits
>with no spaces ?
>
><code>
>#!/usr/bin/env python
>""" a program that takes decimal numbers of any length as space-delimited
>command line arguments and outputs binary numbers separated by newline"""
>
>import sys
>
>dict = {
> '0' : '0000',
> '1' : '0001',
> '2' : '0010',
> '3' : '0011',
> '4' : '0100',
> '5' : '0101',
> '6' : '0110',
> '7' : '0111',
> '8' : '1000',
> '9' : '1001'
> }
>#x = ''
>length = len(sys.argv[1:])
>while length > 0:
> for i in range(length):
> w = sys.argv[-length]
> length = length - 1
> list1 = list(w)
> list1.reverse()
> length2 = len(list1)
> while length2 > 0:
> for i in range(length2):
> w = list1[length2 - 1]
> length2 = length2 - 1
># x.__add__(dict[w])
> x = dict[w]
> print x,
> print '\n'
>
></code>
This program generates Binary Coded Decimal, not Binary. Getting spaces is
an effect of the print statement.
following
length2 = length2 - 1:
try this:
x += dict[w]
print x
FWIW this program is much more complex than needed. You can reduce it to:
dict = {
...
}
for number in sys.argv[1:]: print ''.join([dict[digit] for digit in number])
Bob Gailer
Specialist in evaluating training outcomes.
bgailer@alum.rpi.edu
303 442 2625