Couple functions I need, assuming they exist?
Steven Bethard
steven.bethard at gmail.com
Mon Jun 20 11:38:34 EDT 2005
Charles Krug wrote:
> myWords = split(aString, aChar)
>
> is depreciated but
>
> myWords = aString.split(aChgar)
>
> is not?
Yes, that's basically correct. What's deprecated are the functions in
the string module. So
string.split(a_str, b_str)
is deprecated in favor of
a_str.split(b_str)
> The target of the problems (my daughter) would prefer that the thousands
> be delimited. Is there a string function that does this?
I assume you mean translating something like '1000000' to '1,000,000'?
I don't know of an existing function that does this, but here's a
relatively simple implementation:
py> import itertools as it
py> def add_commas(s):
... rev_chars = it.chain(s[::-1], it.repeat('', 2))
... return ','.join(''.join(three_digits)
... for three_digits
... in it.izip(*[rev_chars]*3))[::-1]
...
py> add_commas('10')
'10'
py> add_commas('100')
'100'
py> add_commas('1000')
'1,000'
py> add_commas('1000000000')
'1,000,000,000'
In case you haven't seen it before, it.izip(*[itr]*N)) iterates over the
'itr' iterator in chunks of size N, discarding the last chunk if it is
less than size N. To avoid losing any digits, I initially pad the
sequence with two empty strings, guaranteeing that only empty strings
are discarded.
So basically, the function iterates over the string in reverse order, 3
characters at a time, and joins these chunks together with commas.
HTH,
STeVe
More information about the Python-list
mailing list