Quick help needed: how to format an integer ?

D

durumdara

Hi !

I need to convert some integer values.

"1622" ->"1 622"

or

"10001234" -> ""10.001.234""

So I need thousand separators.

Can anyone helps me with a simply solution (like %xxx) ?

Thanx for it: dd

Ps:
Now I use this proc:

def toths(i):
s=str(i)
l=[]
ls=len(s)
for i in range(ls):
c=s[ls-i-1]
if i%3==0 and i<>0:
c=c+"."
l.append(c)
l.reverse()
return "".join(l)
 
D

Diez B. Roggisch

Hi !

I need to convert some integer values.

"1622" ->"1 622"

or

"10001234" -> ""10.001.234""

So I need thousand separators.

Can anyone helps me with a simply solution (like %xxx) ?

The module locale does what you need, look at ist docs, especially


locale.str
locale.format


Regards,

Diez
 
P

Paul Rubin

"10001234" -> ""10.001.234""
So I need thousand separators.
Can anyone helps me with a simply solution (like %xxx) ?

I think you're supposed to do a locale-specific conversion (I've never
understood that stuff). You could also do something like this:
if n < 0: return '-' + f(-n)
if n < 1000: return '%d' % n
return f(n//1000) + '.' + '%03d' % (n%1000)
'12.345'
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top