Hi..
I want to do this:
for examle:
12332321 ==12.332.321
How can i do? 22 1924
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
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
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
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!
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.
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
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 ?
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
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
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
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
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
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'
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.
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.
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
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
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
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)
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
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.
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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
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...
|
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...
|
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...
|
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...
|
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...
|
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...
|
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...
|
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...
|
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 ....
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM).
In this month's session, the creator of the excellent VBE...
|
by: DolphinDB |
last post by:
Tired of spending countless mintues downsampling your data? Look no further!
In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
|
by: Aftab Ahmad |
last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below.
Dim IE As Object
Set IE =...
|
by: ryjfgjl |
last post by:
ExcelToDatabase: batch import excel into database automatically...
|
by: marcoviolo |
last post by:
Dear all,
I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, we are pleased to welcome back...
|
by: Vimpel783 |
last post by:
Hello!
Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
|
by: jfyes |
last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
|
by: PapaRatzi |
last post by:
Hello,
I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
| |