[Tutor] Even More Converter!

Rolando Pereira finalyugi at sapo.pt
Sat Mar 22 14:00:20 CET 2008


Kepala Pening wrote:
> import re
> 
> num = 123456789
> 
> print ','.join(re.findall("\d{3}", str(num)))
> 
> output:
> 123,456,789
> 
[snip]

The problem with that is that it cuts the digits in the end of the
number, if they can't form a 3 digit value.

Example:

import re
n = 1234

print ",".join(re.findall("\d{3}", str(n)))

Output: 123, instead of 1,234

I think the use of a function would be better.


def convert_num(num):
	num = map(lambda x: int(x), str(num))
	num.reverse()
	k=0
	tmp_number = []
	for i in range(len(num)):
		if k == 2 and i != range(len(num))[-1]:
			tmp_number.append(num[i])
			tmp_number.append(",")
			k = 0
		else:
			tmp_number.append(num[i])
			k += 1
	num = map(lambda n: str(n), tmp_number)
	num.reverse()
	num = "".join(num)
	return num


First it converts the number into a list in which each digit is a
separate member.

Then it reverses that list (because when we want to add the commas, we
start to count from the right and not from the left, that is, it's 1,234
and not 123,4).

Next a few loop variables (k and tmp_number), and we loop through the
"num" list, appending it's reversed digits into "tmp_number", except
when we have added 2 numbers without adding a comma, so we append the
next number AND a comma.

When the cycle ends, tmp_number is a list of ints with "," string
separating groups of 3 numbers.

In the end, it make "num" the same as "tmp_number", with all it's
members turned to strings (didn't knew that join() only worked with
strings in a list), reverse it (so it returns the same number that was
in the beginning, and joins everything into a string.

Example:

n = 1234
convert_num(n)

Output: 1,234

-- 
                       _
ASCII ribbon campaign ( )
 - against HTML email  X
             & vCards / \


More information about the Tutor mailing list