473,387 Members | 1,512 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

3 number and dot..

Hi..
I want to do this:
for examle:
12332321 ==12.332.321

How can i do?

Oct 31 '07 #1
22 1926
Abandoned wrote:
Hi..
I want to do this:
for examle:
12332321 ==12.332.321

How can i do?

Assuming that the dots are always in the 3rd and 7th position in the string:

def conv(s, sep="."):
l = [s[0:3], s[3:6], s[6:]]
return sep.join(l)

print conv("12332321")
--
pkm ~ http://paulmcnett.com
Oct 31 '07 #2
On Oct 31, 10:18 pm, Paul McNett <p...@ulmcnett.comwrote:
Abandoned wrote:
Hi..
I want to do this:
for examle:
12332321 ==12.332.321
How can i do?

Assuming that the dots are always in the 3rd and 7th position in the string:

def conv(s, sep="."):
l = [s[0:3], s[3:6], s[6:]]
return sep.join(l)

print conv("12332321")

--
pkm ~http://paulmcnett.com
But it's starts from the end..
print conv("12332321")
123.323.21
This is wrong it would be 12.332.321

Oct 31 '07 #3
On Oct 31, 2:58 pm, Abandoned <best...@gmail.comwrote:
Hi..
I want to do this:
for examle:
12332321 ==12.332.321

How can i do?
>>x = (12332321,)
while (x[0]>0): x=divmod(x[0],1000)+x[1:]
....
>>x
(0, 12, 332, 321)
>>".".join(map(str,x[1:]))
'12.332.321'

-- Paul

Oct 31 '07 #4
On Oct 31, 10:38 pm, Paul McGuire <pt...@austin.rr.comwrote:
On Oct 31, 2:58 pm, Abandoned <best...@gmail.comwrote:
Hi..
I want to do this:
for examle:
12332321 ==12.332.321
How can i do?
>x = (12332321,)
while (x[0]>0): x=divmod(x[0],1000)+x[1:]
...
>x
(0, 12, 332, 321)
>".".join(map(str,x[1:]))

'12.332.321'

-- Paul
It's very good thank you paul!

Oct 31 '07 #5
On Oct 31, 2007 3:24 PM, Abandoned <be*****@gmail.comwrote:
On Oct 31, 10:18 pm, Paul McNett <p...@ulmcnett.comwrote:
Abandoned wrote:
Hi..
I want to do this:
for examle:
12332321 ==12.332.321
How can i do?
Assuming that the dots are always in the 3rd and 7th position in the string:

def conv(s, sep="."):
l = [s[0:3], s[3:6], s[6:]]
return sep.join(l)

print conv("12332321")

--
pkm ~http://paulmcnett.com

But it's starts from the end..
print conv("12332321")
123.323.21
This is wrong it would be 12.332.321
If you're doing this for thousands separators, look at the locale module:
>>import locale
locale.setlocale(locale.LC_ALL, 'US') #the default C locale
doesn't do grouping
'English_United States.1252'
>>locale.format_string('%d', 10000, grouping=True)
'10,000'
>>locale.format_string('%d', 12332321, grouping=True)
'12,332,321'
>>>
I only have the US locale available on this machine, but if you use a
locale that uses "." as the thousands separator, this should work for
you.
Oct 31 '07 #6
On 31 oct, 16:58, Abandoned <best...@gmail.comwrote:
Hi..
I want to do this:
for examle:
12332321 ==12.332.321

How can i do?
>>x = 12332321
'.'.join(''.join(i for n, i in g) for k, g in groupby(enumerate(reversed(str(x))), lambda (n, i): n//3))[::-1]
'12.332.321'
>>>
--
Roberto Bonvallet

Oct 31 '07 #7
On Oct 31, 10:38 pm, Paul McGuire <pt...@austin.rr.comwrote:
On Oct 31, 2:58 pm, Abandoned <best...@gmail.comwrote:
Hi..
I want to do this:
for examle:
12332321 ==12.332.321
How can i do?
>x = (12332321,)
while (x[0]>0): x=divmod(x[0],1000)+x[1:]
...
>x
(0, 12, 332, 321)
>".".join(map(str,x[1:]))

'12.332.321'

-- Paul
Hmm.
When the number as 1023 the result is 1.23 :(
How can i fix it ?

Oct 31 '07 #8
elf
On Oct 31, 9:58 pm, Abandoned <best...@gmail.comwrote:
Hi..
I want to do this:
for examle:
12332321 ==12.332.321

How can i do?
If you want do define your own function this will work, no matter how
long the number is, or what separator you choose:

def conv(s, sep='.'):
start=len(s)%3
last=start
result=s[0:start]
for i in range(start+1,len(s)):
if (i-start)%3==0:
if last==0:
result+=s[last:i]
else:
result+=sep+(s[last:i])
last=i

if last==len(s) or last==0:
result+=s[last:len(s)]
else:
result+=sep+s[last:len(s)]
return result

print conv('1234567890000000')
print conv('1')
print conv('123')
print conv('1234')
>>>
1.234.567.890.000.000
1
123
1.234

Oct 31 '07 #9
On Oct 31, 10:50 pm, Roberto Bonvallet <rbonv...@gmail.comwrote:
On 31 oct, 16:58, Abandoned <best...@gmail.comwrote:
Hi..
I want to do this:
for examle:
12332321 ==12.332.321
How can i do?
>x = 12332321
'.'.join(''.join(i for n, i in g) for k, g in groupby(enumerate(reversed(str(x))), lambda (n, i): n//3))[::-1]
'12.332.321'

--
Roberto Bonvallet
Thank you but it give me this error:
NameError: name 'groupby' is not defined

Oct 31 '07 #10
elf
On Oct 31, 9:58 pm, Abandoned <best...@gmail.comwrote:
Hi..
I want to do this:
for examle:
12332321 ==12.332.321

How can i do?
Hi,
If you want to define your own function, no matter what the length of
the number is or what separator you want to choose, this will work:

def conv(s, sep='.'):
start=len(s)%3
last=start
result=s[0:start]
for i in range(start+1,len(s)):
if (i-start)%3==0:
if last==0:
result+=s[last:i]
else:
result+=sep+(s[last:i])
last=i

if last==len(s) or last==0:
result+=s[last:len(s)]
else:
result+=sep+s[last:len(s)]
return result

print conv('1234567890000000')
print conv('1')
print conv('123')
print conv('1234')
>>>
1.234.567.890.000.000
1
123
1.234

Oct 31 '07 #11
On Oct 31, 10:50 pm, Roberto Bonvallet <rbonv...@gmail.comwrote:
On 31 oct, 16:58, Abandoned <best...@gmail.comwrote:
Hi..
I want to do this:
for examle:
12332321 ==12.332.321
How can i do?
>x = 12332321
'.'.join(''.join(i for n, i in g) for k, g in groupby(enumerate(reversed(str(x))), lambda (n, i): n//3))[::-1]
'12.332.321'

--
Roberto Bonvallet
I'm sorry but it give me error "no module named groupby"
My python version is 2.51

Oct 31 '07 #12
Abandoned wrote:
On Oct 31, 10:18 pm, Paul McNett <p...@ulmcnett.comwrote:
>Abandoned wrote:
Hi..
I want to do this:
for examle:
12332321 ==12.332.321
How can i do?

Assuming that the dots are always in the 3rd and 7th position in the string:

def conv(s, sep="."):
l = [s[0:3], s[3:6], s[6:]]
return sep.join(l)

print conv("12332321")
But it's starts from the end..
print conv("12332321")
123.323.21
This is wrong it would be 12.332.321
Ok, my slicing was off by one. Mea culpa. I leave it as an exercise to
fix it. It is really easy, if you understand basic slicing in Python. If
you don't understand slicing, you should google 'python slicing tutorial'.

But, from the other messages in the thread it has become apparent that
you are wanting to group by thousands (that wasn't at all clear in your
initial message).

Chris Mellon has given you the best response: use the locale module for
this. Other people have done all the work for you, all you need to do is
learn how to use locale to get what you want.

It seems like you are looking for a spoonfed solution rather than
looking for guidance on how to solve the problem for yourself. If I'm
wrong about that assessment, I apologize in advance.

Best regards and good luck with your project!
Paul

--
pkm ~ http://paulmcnett.com
Oct 31 '07 #13
Abandoned <be*****@gmail.comwrites:
Hi..
I want to do this:
for examle:
12332321 ==12.332.321

How can i do?
I'm surprised that no one has proposed a regex solution, such as:
>>import re
re.sub(r'\d{1,3}(?=(?:\d{3})+$)', r'\g<0>.', str(1234567))
'1.234.567'
Oct 31 '07 #14
On Wed, 31 Oct 2007 21:39:05 +0000, Abandoned wrote:
On Oct 31, 10:50 pm, Roberto Bonvallet <rbonv...@gmail.comwrote:
>On 31 oct, 16:58, Abandoned <best...@gmail.comwrote:
Hi..
I want to do this:
for examle:
12332321 ==12.332.321
How can i do?
x = 12332321
'.'.join(''.join(i for n, i in g) for k, g in
groupby(enumerate(reversed(str(x))), lambda (n, i): n//3))[::-1]
'12.332.321'

--
Roberto Bonvallet

I'm sorry but it give me error "no module named groupby" My python
version is 2.51
from itertools import groupby

But don't re-invent the wheel. Use the locale module like Chris Mellon
suggested.

--
Steven.
Oct 31 '07 #15
Paul McNett <p@ulmcnett.comwrites:
Chris Mellon has given you the best response: use the locale module
for this.
It may be the best choice as far as reuse is concerned, but it's not
without serious drawbacks.

For one, the locale model doesn't really allow forcing of the
separators. Some locales, such as the "C" locale, define no thousand
separators whatsoever. Since many Unix installations are set up to
use the "C" locale because it is the OS default, this problem must be
addressed. Chris addresse it by forcing the locale to "US", but that
is a step away from the locale model because it consciously overrides
the user's locale preferences. By doing that, one forces a particular
way of grouping thousands, without the possibility to using a
different grouping characters or to group by a different number of
digits (some locales group by tens of thousands). That is quite
similar to what you get when you implement the desired grouping
yourself.

Setting the locale makes the code platform-dependent because different
platforms have different locale names. For example, Chris's code
fails for me with "unsupported locale name" -- apparently, my system
calls the US locale is "en_US.utf8". (Even specifying "en_US" doesn't
work. It might be a Python or system problem, but it just doesn't
work.). Finally, it makes the code OS-installation-dependent -- even
under the same OS, different installs can and do set up different
locales.

If his number presentation calls for thousand separators, coding them
manually is not an unreasonable implementation choice.
It seems like you are looking for a spoonfed solution rather than
looking for guidance on how to solve the problem for yourself. If
I'm wrong about that assessment, I apologize in advance.
No argument here.
Oct 31 '07 #16
Hrvoje Niksic:
I'm surprised that no one has proposed a regex solution, such as:
I presume many Python programmers aren't much used in using REs.

>import re
re.sub(r'\d{1,3}(?=(?:\d{3})+$)', r'\g<0>.', str(1234567))
'1.234.567'
It works with negative numbers too. It's a very nice solution of a
simple problem that shows what you can do with REs. But I think that
RE has to be expanded & splitted (and maybe even commented) with a
VERBOSE, to improve readability, maybe somethign like:

\d {1,3}
(?= # lockahead assertion
(?: \d {3} )+ $ # non-group
)

Bye,
bearophile

Oct 31 '07 #17
On Oct 31, 7:58 pm, Abandoned <best...@gmail.comwrote:
Hi..
I want to do this:
for examle:
12332321 ==12.332.321

How can i do?
Short without being too unreadable:

def conv(x, sep='.'):
x = str(x)[::-1]
return sep.join(x[i:i + 3] for i in range(0, len(x), 3))[::-1]

Or more simple-mindedly...

def conv(x, sep='.'):
x, y = str(x), []
while x:
y.append(x[-3:])
x = x[:-3]
return sep.join(reversed(y))

--
Paul Hankin

Oct 31 '07 #18
On Oct 31, 7:32 pm, bearophileH...@lycos.com wrote:
Hrvoje Niksic:
I'm surprised that no one has proposed a regex solution, such as:

I presume many Python programmers aren't much used in using REs.
>>import re
>>re.sub(r'\d{1,3}(?=(?:\d{3})+$)', r'\g<0>.', str(1234567))
'1.234.567'

It works with negative numbers too. It's a very nice solution of a
simple problem that shows what you can do with REs. But I think that
RE has to be expanded & splitted (and maybe even commented) with a
VERBOSE, to improve readability, maybe somethign like:

\d {1,3}
(?= # lockahead assertion
(?: \d {3} )+ $ # non-group
)

Bye,
bearophile

That's 3 times faster on my box and works for negatives too:

def localize(num, sep='.'):
d,m = divmod(abs(num),1000)
return '-'*(num<0) + (localize(d)+sep+'%03d'%m if d else str(m))
George

Nov 1 '07 #19
Abandoned <be*****@gmail.comwrites:
12332321 ==12.332.321
Untested:

def convert(n):
assert type(n) in (int,long)
if n < 0: return '-%s'% convert(-n)
if n < 1000: return str(n)
return '%s.%03d' % (convert(n//1000), n % 1000)
Nov 1 '07 #20
On 31 oct, 22:21, Paul Rubin <http://phr...@NOSPAM.invalidwrote:
def convert(n):
assert type(n) in (int,long)
I'd replace this line with n = int(n), more in the spirit of duck
typing.

--
Roberto Bonvallet

Nov 2 '07 #21
On Fri, 02 Nov 2007 16:39:12 +0000, Roberto Bonvallet wrote:
On 31 oct, 22:21, Paul Rubin <http://phr...@NOSPAM.invalidwrote:
>def convert(n):
assert type(n) in (int,long)

I'd replace this line with n = int(n), more in the spirit of duck
typing.
Not necessarily. Something duck typing is too liberal in what it accepts.
You might want convert(math.pi) to raise an exception, although I'd
suggestion an assert is the wrong test. A better test would be an
explicit type check with raise:

if not isinstance(n, (int, long)):
raise TypeError('n not an integer')
assert is for "this can never happen" tests rather than type checking.

--
Steven.
Nov 2 '07 #22
On 2 nov, 14:54, Steven D'Aprano <st...@REMOVE-THIS-
cybersource.com.auwrote:
Not necessarily. Something duck typing is too liberal in what it accepts.
You might want convert(math.pi) to raise an exception
What I meant was that the function should not reject unnecessarily non-
numeric
things that can be converted to a number, like a string. However,
you're right:
numeric things that are not integers should not be treated silently as
if they
were.
although I'd suggestion an assert is the wrong test. A better test would be an
explicit type check with raise.
I completely agree.

Cheers,
--
Roberto Bonvallet
Nov 2 '07 #23

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Shay Hurley | last post by:
this is probably a stupid question so apologies in advance. I am trying to format a number to look like a phone number with "-"'s between the numbers etc e.g. 15554256987 should be formatted as...
8
by: EAS | last post by:
Hey, I'm new to python (and programming in general) so I'll prolly be around here a lot... Anyways, I've found out how to make a "guess my number game" where the player guesses a number between...
11
by: don | last post by:
Ok, this is a homework assignment, but can you help me out anyway...... I need a routine for figuring out if a number inputted by the user is a prime number or not...... all I'm asking for is Not...
27
by: Gaijinco | last post by:
Sooner or later everytime I found recreational programming challenges I stumble with how I test if a number is has decimal places differnt than 0? For example if I want to know if a number is a...
13
by: Ron | last post by:
Hi all I'm deciding whether to use the PK also as an account number, invoice number, transaction number, etc that the user will see for the respective files. I understand that sometimes a...
19
by: gk245 | last post by:
Trying to write a program that will figure out if a number is perfect or not. Here is my logic: 1) Read in the number 2) Split it up (number - 1) 3) Put all the split up numbers into an...
4
by: SweetLeftFoot | last post by:
Hello, i have designed some code that works out the first 250 prime numbers and prints them to the screen. However i need to implement 2 functions, one of which returns a 1 if the number is a prime...
4
by: fatimahtaher | last post by:
Hi, I am supposed to create a program that generates a random number and then asks the user to guess the number (1-100). The program tells the user if he guessed too high or too low. If he...
5
by: silversnake | last post by:
I'm trying to write a program that take a input number and prints if is a prime numbers but is not working for instance, it says that 4 is prime while 5 is not. can anyone see what the problem is ....
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.