[Tutor] python string __add__
Alan Gauld
alan.gauld@blueyonder.co.uk
Thu Jun 5 19:22:45 2003
> I have a script that will take decimal numbers of any length as
command
> line arguments and output the binary equivalent.
Its probably easier to just use the mathematical algorithm for
converting numbers using repeated modulo division, however....
> spaces. Is there a way for python string __add__ to output
> binary digits with no spaces ?
> """ a program that takes decimal numbers of any length as
> space-delimited command line arguments and outputs binary
> numbers separated by newline"""
I take that to mean:
foo 123456 234 98765433456789007 4
[----
Or do you mean:
foo 1 2 3 4 5 6 7 8 9 6 7 8 3 4 7 2 1 4
I'm not sure... An example is ghood in a doc string...
---]
> dict = {
> '0' : '0000',
> '1' : '0001',
etc
> '9' : '1001'
> }
BTW You have just lost the ability to convert to a dict type
by stealing the name as a variable... probably a bad idea!
> length = len(sys.argv[1:])
> while length > 0:
> for i in range(length):
> w = sys.argv[-length]
> length = length - 1
That's a complicated way of stepping through each number
in the command string.
for w in sys.argv[1:]:
> list1 = list(w)
> list1.reverse()
> length2 = len(list1)
> while length2 > 0:
> for i in range(length2):
> w = list1[length2 - 1] # w = list1[-1]??
> length2 = length2 - 1
I *think" this just reads the characters (digits) in reverse order.
But since you already reversed the list why not miss all the hassle
and just read them in normal order:
for i in w:
> # x.__add__(dict[w])
You should never call a python operator function like that.
You probably should do something like:
x = x + dict[w]
> x = dict[w]
This will convert your numbers into binary coded decimal not true
binary. ie you are simply converting each digit into its binary
equivalent and concatenating them.
eg
decimal BCD binary
8 1000 1000 OK so far
15 00010101 1111 Oops!
None of that actually answers your question about string
concatenation!
Try:
s = "%s%s" % (string1,string2)
OR
s = string1 + string2
s will contain the two strings joined together with no spaces.
HTH,
Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld