String Formatting

2006-08-10 Thread OriginalBrownster
Hi there:

I was wondering if its at all possible to search through a string for a
specific character.

I want to search through a string backwords and find the last
period/comma, then take everything after that period/comma

Example

If i had a list:bread, butter, milk

I want to just take that last entry of milk. However the need for it
arises from something more complicated.

Any help would be appreciated

-- 
http://mail.python.org/mailman/listinfo/python-list


String formatting strangeness

2005-05-13 Thread dark . ryder
I must be doing something wrong, but for the life of me, I can't figure
out what.  Here's the code snippet which is giving me grief:

print type(number), type(name), type(seconds // 60), type(seconds % 60)
print "\t\t\t\n"
% [number, name, seconds // 60, seconds % 60]

(These are lines 49 and 50 of the script; I can post the whole thing if
someone wants, but I think this is enough to see why it's driving me
nuts.)

And the output:

   
Traceback (most recent call last):
  File "X:\Music (FLAC)\Post-process new rips.py", line 50, in ?
print "\t\t\t\n" % [number, name, seconds // 60, seconds % 60]
TypeError: int argument required

Wait, what?  The first line clearly identifies that the the first,
third, and fourth elements are all integers, yet the error says that
*lack* of integers is the problem.  If I change all "%i"s to "%d", I
get the same problem, and changing to "%s" (hey, it was worth a shot)
gives "TypeError: not enough arguments for format string" instead.
Huh?  I see four placeholders and a four-element tuple.

Can anyone enlighten me here?

-- 
http://mail.python.org/mailman/listinfo/python-list


string formatting quirk?

2005-05-20 Thread [EMAIL PROTECTED]
Hi,

''%([]) doesn't raise exception
but
''%('') does

Can anyone explain me why??

rgds
Anurag

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String Formatting

2006-08-10 Thread Avell Diroll
OriginalBrownster wrote:
> Hi there:
> 
> I was wondering if its at all possible to search through a string for a
> specific character.
> 
> I want to search through a string backwords and find the last
> period/comma, then take everything after that period/comma
> 
> Example
> 
> If i had a list:bread, butter, milk
> 
> I want to just take that last entry of milk. However the need for it
> arises from something more complicated.
> 
> Any help would be appreciated
> 



Would that work for you ?

>>> a = 'bread, butter, milk'
>>> a
'bread, butter, milk'
>>> b = a.split(',')
>>> b
['bread', ' butter', ' milk']
>>> c = b[-1]
>>> c
' milk'
>>> d = c.strip()
>>> d
'milk'




HIH


Avell

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String Formatting

2006-08-10 Thread Pontus Ekberg
On Thu, 10 Aug 2006 05:35:26 -0700, OriginalBrownster wrote:

> Hi there:
> 
> I was wondering if its at all possible to search through a string for a
> specific character.
> 
> I want to search through a string backwords and find the last
> period/comma, then take everything after that period/comma
> 
> Example
> 
> If i had a list:bread, butter, milk
> 
> I want to just take that last entry of milk. However the need for it
> arises from something more complicated.
> 
> Any help would be appreciated


>>> s='bread, butter, milk'
>>> s.rsplit(',', 1)[-1]
' milk'
>>> s.rsplit(',', 1)[-1].strip()
'milk'


Hope that helps.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String Formatting

2006-08-10 Thread Simon Forman
OriginalBrownster wrote:
> Hi there:
>
> I was wondering if its at all possible to search through a string for a
> specific character.
>
> I want to search through a string backwords and find the last
> period/comma, then take everything after that period/comma
>
> Example
>
> If i had a list:bread, butter, milk
>
> I want to just take that last entry of milk. However the need for it
> arises from something more complicated.
>
> Any help would be appreciated

The rfind() method of strings will search through a string for the
first occurance of a substring, starting from the end.  (find() starts
from the beginning.)

|>> s = "bread, butter, milk"
|>> s.rfind(',')
13
|>> s.rfind('!')
-1
|>> s[s.rfind(',') + 1:]
' milk'

If you want to find either a period or comma you could do it like this:

|>> i = max(s.rfind(ch) for ch in ',.')
|>> i
13
|>> s[i + 1:]
' milk'

Here's the output of help(s.rfind):
Help on built-in function rfind:

rfind(...)
S.rfind(sub [,start [,end]]) -> int

Return the highest index in S where substring sub is found,
such that sub is contained within s[start,end].  Optional
arguments start and end are interpreted as in slice notation.

Return -1 on failure.


Enjoy


Peace,
~Simon

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String Formatting

2006-08-10 Thread alisonken1

OriginalBrownster wrote:

> Example
>
> If i had a list:bread, butter, milk

def get_word(s, which=1, sep=','):
return s.split(sep)[which-1].strip()

>>>
>>> get_word('bread, butter, milk')
'milk'

>>>

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String Formatting

2006-08-10 Thread alisonken1

alisonken1 wrote:
> OriginalBrownster wrote:
> 
> > Example


sorry, forgot the '... everything after the last comma ...' part.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String Formatting

2006-08-10 Thread alisonken1
Sorry, missed an option in there:

> def get_word(s, which=1, sep=','):
> return s.split(sep)[which-1].strip()
>
> >>>
> >>> get_word('bread, butter, milk')
> 'milk'
>
> >>>

>>> get_word('bread, butter, milk')
'bread'

>>> get_word('bread, butter, milk', 3)
'milk'

>>> get_word('bread is brown, butter is yellow, milk is white')
'bread is brown'

>>> get_word('bread is brown, butter is yello, milk is white', 3)
'milk is white'

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String Formatting

2006-08-10 Thread John Machin
OriginalBrownster wrote:
> Hi there:
>
> I was wondering if its at all possible to search through a string for a
> specific character.

Don't wonder; read the tutorials, read the manuals, and ponder the
sheer uselessness of any computer language that offered neither such a
facility nor the means to build it yourself.

>
> I want to search through a string backwords and find the last
> period/comma, then take everything after that period/comma


>
> Example
>
> If i had a list:bread, butter, milk
>
> I want to just take that last entry of milk. However the need for it
> arises from something more complicated.
>

Python terminology: that's not a list, it's a string.

> Any help would be appreciated

If you already know that you are looking for a comma, then the
following will do the job. If you know that you are looking for a
period, make the obvious substitution.

>>> x = " bread, butter, milk "
>>> x.split(",")
[' bread', ' butter', ' milk ']
>>> x.split(",")[-1]
' milk '
>>> x.split(",")[-1].strip()
'milk'
>>> x = " no commas at all "
>>> x.split(",")
[' no commas at all ']
>>> x.split(",")[-1]
' no commas at all '
>>> x.split(",")[-1].strip()
'no commas at all'
>>>

*HOWEVER* if you really mean what you said (i.e. start at the
rightmost, go left until you strike either a comma or a period,
whichever comes first) then you need something like this:

>>> def grab_last_chunk(s):
...return s[max(s.rfind(','), s.rfind('.')) + 1:]
...
>>> grab_last_chunk(" bread, butter, milk ")
' milk '
>>> grab_last_chunk(" bread, butter. milk ")
' milk '
>>> grab_last_chunk(" bread! butter! milk ")
' bread! butter! milk '
>>> grab_last_chunk(" bread, butter, milk.")
''
>>>

The serendipity in the above is that if the sought character is not
found, rfind() returns -1 which fits in nicely without the need for an
"if" statement to do something special.

HTH,
John

-- 
http://mail.python.org/mailman/listinfo/python-list


None in string formatting

2005-03-08 Thread rodney . maxwell
Was doing some string formatting, noticed the following:

>>> x = None
>>> "%s" % x
'None'

Is there a reason it maps to 'None'? I had expected ''.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String formatting strangeness

2005-05-13 Thread Peter Hansen
[EMAIL PROTECTED] wrote:
> I must be doing something wrong, but for the life of me, I can't figure
> out what.  Here's the code snippet which is giving me grief:
> 
> print type(number), type(name), type(seconds // 60), type(seconds % 60)
> print "\t\t\t\n"
> % [number, name, seconds // 60, seconds % 60]
[snip]
> 
> Wait, what?  The first line clearly identifies that the the first,
> third, and fourth elements are all integers, yet the error says that
> *lack* of integers is the problem.  If I change all "%i"s to "%d", I
> get the same problem, and changing to "%s" (hey, it was worth a shot)
> gives "TypeError: not enough arguments for format string" instead.
> Huh?  I see four placeholders and a four-element tuple.

Nope, you see a four-element list.  Try changing it to a tuple... ;-)

-Peter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String formatting strangeness

2005-05-13 Thread Larry Bates
The argument to string format expression needs to be a tuple not a list.

Also, all the string escaping makes this very hard to read.  You can
mix single and double quotes to achieve:

print '\t\t\t\n' % \
  (number, name, seconds // 60, seconds % 60)

which IMHO is much easier to read.

Larry Bates

[EMAIL PROTECTED] wrote:
> I must be doing something wrong, but for the life of me, I can't figure
> out what.  Here's the code snippet which is giving me grief:
> 
> print type(number), type(name), type(seconds // 60), type(seconds % 60)
> print "\t\t\t\n"
> % [number, name, seconds // 60, seconds % 60]
> 
> (These are lines 49 and 50 of the script; I can post the whole thing if
> someone wants, but I think this is enough to see why it's driving me
> nuts.)
> 
> And the output:
> 
>
> Traceback (most recent call last):
>   File "X:\Music (FLAC)\Post-process new rips.py", line 50, in ?
> print "\t\t\t length=\"%i:%i\"/>\n" % [number, name, seconds // 60, seconds % 60]
> TypeError: int argument required
> 
> Wait, what?  The first line clearly identifies that the the first,
> third, and fourth elements are all integers, yet the error says that
> *lack* of integers is the problem.  If I change all "%i"s to "%d", I
> get the same problem, and changing to "%s" (hey, it was worth a shot)
> gives "TypeError: not enough arguments for format string" instead.
> Huh?  I see four placeholders and a four-element tuple.
> 
> Can anyone enlighten me here?
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String formatting strangeness

2005-05-13 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

>
> Traceback (most recent call last):
>   File "X:\Music (FLAC)\Post-process new rips.py", line 50, in ?
> print "\t\t\t length=\"%i:%i\"/>\n" % [number, name, seconds // 60, seconds % 60]
> TypeError: int argument required
>
> Wait, what?  The first line clearly identifies that the the first,
> third, and fourth elements are all integers, yet the error says that
> *lack* of integers is the problem.  If I change all "%i"s to "%d", I
> get the same problem, and changing to "%s" (hey, it was worth a shot)
> gives "TypeError: not enough arguments for format string" instead.
> Huh?  I see four placeholders and a four-element tuple.

[number, name, seconds // 60, seconds % 60] is not a tuple.

(number, name, seconds // 60, seconds % 60) is a tuple.





-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String formatting strangeness

2005-05-13 Thread dark . ryder
*hides face*  Groan!  This is what I get for trying to code first thing
in the morning.  Thanks, all, it works fine now...

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: string formatting quirk?

2005-05-20 Thread Peter Otten
[EMAIL PROTECTED] wrote:

> ''%([]) doesn't raise exception
> but
> ''%('') does
> 
> Can anyone explain me why??

That is a side-effect of duck-typing. The duck-type of an empty list is
indistinguishable from that of an empty dictionary. Not testing the exact
type here achieves consistency with the behaviour of custom dictionaries,
e. g: 

>>> class List(list):
... def __getitem__(self, index):
... return list.__getitem__(self, int(index))
...
>>> "%(0)s" % List([42])
'42'
>>> "%(1)s %(0)s" % List([42, 24])
'24 42'
>>> "" % List([])
''

Peter

-- 
http://mail.python.org/mailman/listinfo/python-list


Hidden string formatting bug

2005-10-13 Thread Echo
Hello,
I have been trying to figure out the problem with this string formatting:

sql = 'INSERT INTO tc_themes (name,user_made,hour12,time_loc,background_color_r,' + \
   
'background_color_g,background_color_b,clock_color_r,clock_color_g,' + \
   
'clock_color_b,clock_background_color_r,clock_background_color_g,' + \
   
'clock_background_color_b,clock_points_color_r,clock_points_color_g,' +
\
   
'clock_points_color_b,clock_hour_color_r,clock_hour_color_g,' + \
   
'clock_hour_color_b,clock_min_color_r,clock_min_color_g,' + \
   
'clock_min_color_b,clock_sec_color_r,clock_sec_color_g,' + \
   
'clock_sec_color_b,clock_font_facename,clock_font_size,' + \
   
'clock_font_style,clock_font_underlined,clock_font_weight,' + \
   
'clock_font_color_r,clock_font_color_g,clock_font_color_b,' + \
   
'time_font_facename,time_font_size,time_font_style,' + \
   
'time_font_underlined,time_font_weight,time_font_color_r,' + \
   
'time_font_color_g,time_font_color_b) VALUES (' + \
    "%s,%i,%i,%s,%i," + \
    "%i,%i,%i,%i," + \
    "%i,%i,%i," + \
    "%i,%i,%i," + \
    "%i,%i,%i," + \
    "%i,%i,%i," + \
    "%i,%i,%i," + \
    "%i,%s,%i," + \
    "%i,%i,%i," + \
    "%i,%i,%i," + \
    "%s,%i,%i," + \
    "%i,%i,%i," + \
   
"%i,%i)" % ("'Simple Clock'", 0, 1, "'Top'", 200, 200, 200, 100, 100,
100, 255, 255, 255, 100, 100, 100, 0, 0, 0, 0, 0, 0, 255, 0, 0,
"'Arial'", 18, 90, 0, 90, 0, 0, 0, "'Arial'", 32, 90, 0, 90, 0, 0, 0)

when it executes, I get this error: "inv argument required". I have
checked and rechecked both the string and the tuple. I cant figure out
what the problem is.
After playing around with it, i found out if change the last line to:
"%s,%i) %(... I get a different error. The error is "not all arguments
converted during string formatting".

So I am baffled and confused as of why this wont work. Is anyone able to shed some light on my hidden bug?
Using: Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)]
-- -Echo
-- 
http://mail.python.org/mailman/listinfo/python-list

String formatting using dictionaries

2006-04-22 Thread Clodoaldo Pinto
I know how to format strings using a dictionary:

>>> d = {'list':[0, 1]}
>>> '%(list)s' % d
'[0, 1]'

Is it possible to reference an item in the list d['list']?:

>>> '%(list[0])s' % d
Traceback (most recent call last):
  File "", line 1, in ?
KeyError: 'list[0]'

Regards, Clodoaldo Pinto

-- 
http://mail.python.org/mailman/listinfo/python-list


Simple string formatting question

2006-04-06 Thread Steven D'Aprano
I have a sinking feeling I'm missing something really, 
really simple.

I'm looking for a format string similar to '%.3f' 
except that trailing zeroes are not included.

To give some examples:

FloatString
1.0  1
1.1  1.1
12.1234  12.123
12.0001  12

and similar.

Here is a (quick and dirty) reference implementation:

def format(f, width=3):
 fs = '%%.%df' % width
 s = fs % f
 return s.rstrip('0').rstrip('.')


Is there a way of getting the same result with just a 
single string format expression?



-- 
Steven

-- 
http://mail.python.org/mailman/listinfo/python-list


Reverse string-formatting (maybe?)

2006-10-14 Thread Dustan
Is there any builtin function or module with a function similar to my
made-up, not-written deformat function as follows? I can't imagine it
would be too easy to write, but possible...

>>> template = 'I am %s, and he %s last %s.'
>>> values = ('coding', "coded', 'week')
>>> formatted = template % values
>>> formatted
'I am coding, and he coded last week.'
>>> deformat(formatted, template)
('coding', 'coded', 'week')

expanded (for better visual):
>>> deformat('I am coding, and he coded last week.', 'I am %s, and he %s last 
>>> %s.')
('coding', 'coded', 'week')

It would return a tuple of strings, since it has no way of telling what
the original type of each item was.


Any input? I've looked through the documentation of the string module
and re module, did a search of the documentation and a search of this
group, and come up empty-handed.

-- 
http://mail.python.org/mailman/listinfo/python-list


string formatting: engineering notation

2007-03-14 Thread Darren Dale
Does anyone know if it is possible to represent a number as a string with
engineering notation (like scientific notation, but with 10 raised to
multiples of 3: 120e3, 12e-6, etc.). I know this is possible with the
decimal.Decimal class, but repeatedly instantiating Decimals is inefficient
for my application (matplotlib plotting library). If it is not currently
possible, do you think the python devs would be receptive to including
support for engineering notation in future releases?

Thanks,
Darren
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: None in string formatting

2005-03-08 Thread Steven Bethard
[EMAIL PROTECTED] wrote:
Was doing some string formatting, noticed the following:
x = None
"%s" % x
'None'
Is there a reason it maps to 'None'? I had expected ''.
Can you explain why you expected that?  A few other examples that make 
me not expect what you do:

py> '%s' % False
'False'
py> '%s' % []
'[]'
py> '%s' % {}
'{}'
py> '%s' % set()
'set([])'
All of the objects above evaluate to False in a boolean context like '' 
does, but they display a string appropriate to their type.  Since None 
has it's own type (NoneType), I would expect similar behavior.

STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Re: None in string formatting

2005-03-08 Thread Jorge Godoy
[EMAIL PROTECTED] writes:

> Was doing some string formatting, noticed the following:
> 
> >>> x = None
> >>> "%s" % x
> 'None'
> 
> Is there a reason it maps to 'None'? I had expected ''.

How would know, then, if there was no value at all or if it was an empty
string? 

-- 
Godoy.  <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: None in string formatting

2005-03-08 Thread Scott David Daniels
Jorge Godoy wrote:
[EMAIL PROTECTED] writes:
Was doing some string formatting, noticed the following:
x = None
"%s" % x
'None'
Is there a reason it maps to 'None'? I had expected ''.
How would know, then, if there was no value at all or if it was an empty
string? 

If you want the other effect, you can always do:
"%s" % (x or '')
--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: None in string formatting

2005-03-08 Thread Steve Holden
Jorge Godoy wrote:
[EMAIL PROTECTED] writes:

Was doing some string formatting, noticed the following:

x = None
"%s" % x
'None'
Is there a reason it maps to 'None'? I had expected ''.

How would know, then, if there was no value at all or if it was an empty
string? 

Well, for that matter, how can you tell the difference between
'%s' % False
and
'%s' % 'False'
since both inevitably produce the same output.
The bottom line is that you are trying to map the strings plus other 
values on to the strings, which means it's a mathematical certainty 
there will be ambiguities. It's just that you want *your* preferred 
ambiguities rather than what Python gives you.

Suppose Python were to do what you want, how could you distinguish 
between the outputs for "" and None? Of course, at the moment the 
outputs for "None" and None are the same, but that just supports my 
assertion about the inevitability of ambiguities.

regards
 Steve
--
http://mail.python.org/mailman/listinfo/python-list


Re: None in string formatting

2005-03-08 Thread Erik Max Francis
[EMAIL PROTECTED] wrote:
Was doing some string formatting, noticed the following:
x = None
"%s" % x
'None'
Is there a reason it maps to 'None'? I had expected ''.
Because %s just calls str on the arguments, and str(None) == 'None'.
--
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
  As far as I'm concerned, being any gender is a drag.
  -- Patti Smith
--
http://mail.python.org/mailman/listinfo/python-list


Re: Hidden string formatting bug

2005-10-13 Thread Tim Peters
[Echo]
> I have been trying to figure out the problem with this string formatting:

[monstrous statement snipped]

> when it executes, I get this error: "inv argument required".

That shoud be "int", not "inv".

> I have checked and rechecked both the string and the tuple. I cant figure
> out what the problem is.  After playing around with it, i found out if change
> the last line to: "%s,%i) %(... I get a different error. The error is "not all
> arguments converted during string formatting".
>
> So I am baffled and confused as of why this wont work. Is anyone able to
> shed some light on my hidden bug?

Yup, it's precedence.  Here's the same thing:

sql = "%s" + \
  "%i" % ("abc", 2)

Run that and you get "int argument required".  Change the last %i to
%s and you get "not all arguments converted during string formatting".
 Both error messages are accurate.

That's because % binds tighter than "+".  As a 1-liner, and inserting
redundant parentheses to make the precedence obvious, my simplified
example is

sql = "%s" + ("%i" % ("abc", 2))

What you intended _requires_ inserting more parentheses to force the
intended order (if you're going to stick to this confusing coding
style):

sql = ("%s" + "%i") % ("abc", 2)

Better is to not use "+" on string literals, and not use backslash
continuation either; try this instead:

sql_format = ('string1'
'string2'
'string3'
...
'last string')

Build the format in a separate statement to reduce the chance of
errors (for example, your original mistake would have been impossible
to make this way).  Use parens instead of backslashes.  Don't use "+"
to catenate string literals:  the Python compiler automatically
catenates adjacent string literals for you, and at compile-time (so
it's even more efficient than using '"+").
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Hidden string formatting bug

2005-10-13 Thread Steve Holden
Tim Peters wrote:
> [Echo]
> 
>>I have been trying to figure out the problem with this string formatting:
> 
> 
> [monstrous statement snipped]
> 
> 
>>when it executes, I get this error: "inv argument required".
> 
> 
> That shoud be "int", not "inv".
> 
> 
>>I have checked and rechecked both the string and the tuple. I cant figure
>>out what the problem is.  After playing around with it, i found out if change
>>the last line to: "%s,%i) %(... I get a different error. The error is "not all
>>arguments converted during string formatting".
>>
>>So I am baffled and confused as of why this wont work. Is anyone able to
>>shed some light on my hidden bug?
> 
> 
> Yup, it's precedence.  Here's the same thing:
> 
> sql = "%s" + \
>   "%i" % ("abc", 2)
> 
> Run that and you get "int argument required".  Change the last %i to
> %s and you get "not all arguments converted during string formatting".
>  Both error messages are accurate.
> 
> That's because % binds tighter than "+".  As a 1-liner, and inserting
> redundant parentheses to make the precedence obvious, my simplified
> example is
> 
> sql = "%s" + ("%i" % ("abc", 2))
> 
> What you intended _requires_ inserting more parentheses to force the
> intended order (if you're going to stick to this confusing coding
> style):
> 
> sql = ("%s" + "%i") % ("abc", 2)
> 
> Better is to not use "+" on string literals, and not use backslash
> continuation either; try this instead:
> 
> sql_format = ('string1'
> 'string2'
> 'string3'
> ...
> 'last string')
> 
> Build the format in a separate statement to reduce the chance of
> errors (for example, your original mistake would have been impossible
> to make this way).  Use parens instead of backslashes.  Don't use "+"
> to catenate string literals:  the Python compiler automatically
> catenates adjacent string literals for you, and at compile-time (so
> it's even more efficient than using '"+").

Further to Tim's erudite language advice, I should point out the 
oft-repeated advice that you are leaving yourself wide open to SQL 
injection exploits here, and you should definitely consider using 
parameterised queries, which have been discussed here so often (and too 
recently for me to repeat) that you should easily be able to find them 
with Google.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

-- 
http://mail.python.org/mailman/listinfo/python-list


string formatting using the % operator

2005-06-13 Thread William Gill
I am using the % operator to create queries for a db app.  It works fine 
when exact strings, or numbers are used, but some queries need partial 
matching that use the '%' as a wildcards. So for example the resultant 
string should be 'WHERE name LIKE %smith%'  (would match silversmith, 
smithy, and smith).  Is there any way to get something like

   searchterm = 'smith'
   sql += 'WHERE name LIKE %s'  %  searchterm

to return 'WHERE name LIKE %smith%'I have tried using escapes, 
character codes for the % sign, and lots of other gyrations with no 
success.  The only thing that works is if I modify searchterm first:

   searchterm = 'smith'
   searchterm ='%'+'smith'+'%'
   sql += 'WHERE name LIKE %s'  %  searchterm

Any Ideas?

Thanks,
Bill
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String formatting using dictionaries

2006-04-22 Thread Peter Otten
Clodoaldo Pinto wrote:

> I know how to format strings using a dictionary:
> 
 d = {'list':[0, 1]}
 '%(list)s' % d
> '[0, 1]'
> 
> Is it possible to reference an item in the list d['list']?:
> 
 '%(list[0])s' % d
> Traceback (most recent call last):
>   File "", line 1, in ?
> KeyError: 'list[0]'

No, but you can provide a modified dictionary to get the effect:

>>> class Dict(dict):
... def __getitem__(self, key):
... if key in self:
... return super(Dict, self).__getitem__(key)
... return eval(key, self)
...
>>> d = Dict(list=[0, 1])
>>> "%(list)s" % d
'[0, 1]'
>>> "%(list[0])s" % d
'0'
>>> "%(list[1]+42)s" % d
'43'

Peter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String formatting using dictionaries

2006-04-22 Thread Fredrik Lundh
Clodoaldo Pinto wrote:

> I know how to format strings using a dictionary:
>
> >>> d = {'list':[0, 1]}
> >>> '%(list)s' % d
> '[0, 1]'
>
> Is it possible to reference an item in the list d['list']?:
>
> >>> '%(list[0])s' % d
> Traceback (most recent call last):
>   File "", line 1, in ?
> KeyError: 'list[0]'

not directly, but you can wrap the dictionary in a custom mapper
class:

class mapper(dict):
def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except KeyError:
k, i = key.split("[")
i = int(i[:-1])
return dict.__getitem__(self, k)[i]

>>> d = {"list": [0, 1]}
>>> d = mapper(d)
>>> '%(list)s' % d
[0, 1]
>>> '%(list[0])s' % d
0





-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String formatting using dictionaries

2006-04-22 Thread Clodoaldo Pinto
Thank you guys, you are great!

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple string formatting question

2006-04-06 Thread Ben Finney
"Steven D'Aprano" <[EMAIL PROTECTED]> writes:

> I have a sinking feeling I'm missing something really, really
> simple.

"Oh no, everyone in the galaxy gets that, that's perfectly natural
paranoia."

> I'm looking for a format string similar to '%.3f' except that
> trailing zeroes are not included.

Can;t be done, to my knowledge. You specify a particular precision,
and the number will be formatted at that precision. This matches the
'printf' behaviour that inspired string formatting operations.

If your brute-force approach works, stick to that until you have a
reason to look for something better.

-- 
 \ "I have an answering machine in my car. It says, 'I'm home now. |
  `\  But leave a message and I'll call when I'm out.'"  -- Steven |
_o__)   Wright |
Ben Finney

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple string formatting question

2006-04-06 Thread Fredrik Lundh
Steven D'Aprano wrote:

> Here is a (quick and dirty) reference implementation:
>
> def format(f, width=3):
> fs = '%%.%df' % width
> s = fs % f
> return s.rstrip('0').rstrip('.')
>
> Is there a way of getting the same result with just a
> single string format expression?

not with % itself, but you can do it all in one line:

def format(f, width=3): return ("%.*f" % (width, f)).rstrip(".0")

 



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple string formatting question

2006-04-06 Thread Paul McGuire
"Fredrik Lundh" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Steven D'Aprano wrote:
>
> > Here is a (quick and dirty) reference implementation:
> >
> > def format(f, width=3):
> > fs = '%%.%df' % width
> > s = fs % f
> > return s.rstrip('0').rstrip('.')
> >
> > Is there a way of getting the same result with just a
> > single string format expression?
>
> not with % itself, but you can do it all in one line:
>
> def format(f, width=3): return ("%.*f" % (width, f)).rstrip(".0")
>
> 
>
>
>
Ooops, don't combine the two calls to rstrip().

def format(f, width=3): return ("%.*f" % (width, f)).rstrip(".0")

print format(3.140)
print format(3.000)
print format(3.001)
print format(30.)
print format(30.000)

Gives:
3.14
3
3
3
3

But this works fine:
def format(f, width=3): return ("%.*f" % (width, f)).rstrip("0").rstrip(".")


-- Paul




-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple string formatting question

2006-04-06 Thread Steven D'Aprano
On Thu, 06 Apr 2006 22:16:05 +1000, Ben Finney wrote:

> "Steven D'Aprano" <[EMAIL PROTECTED]> writes:

>> I'm looking for a format string similar to '%.3f' except that
>> trailing zeroes are not included.
> 
> Can;t be done, to my knowledge. You specify a particular precision,
> and the number will be formatted at that precision. This matches the
> 'printf' behaviour that inspired string formatting operations.
> 
> If your brute-force approach works, stick to that until you have a
> reason to look for something better.

Thanks to everybody who replied, I'm glad to see I didn't miss anything.

I do actually have a reason for wanting a single format pattern, but I can
probably work with what I have, it will just be less convenient.

I hesitate to suggest this, what with the whole PEP procedure and all
being so intimidating to those who aren't familiar with it (e.g. me), but
would there be any interest in extending the formatting operations to
include such a feature? It would (presumably) break compatibility with
printf, but does that matter?



-- 
Steven.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple string formatting question

2006-04-06 Thread Ben Finney
"Steven D'Aprano" <[EMAIL PROTECTED]> writes:

> On Thu, 06 Apr 2006 22:16:05 +1000, Ben Finney wrote:
> > "Steven D'Aprano" <[EMAIL PROTECTED]> writes:
1> >> I'm looking for a format string similar to '%.3f' except that
> >> trailing zeroes are not included.
> > 
> > Can;t be done, to my knowledge. You specify a particular
> > precision, and the number will be formatted at that
> > precision. This matches the 'printf' behaviour that inspired
> > string formatting operations.
> 
> [...] would there be any interest in extending the formatting
> operations to include such a feature? It would (presumably) break
> compatibility with printf, but does that matter?

-1 from me. The concept of "precision" is fairly well defined; you're
talking about combining that with something more special-case.  In
general, "special cases aren't special enough to break the rules", and
the programemr should be forced to spell out what he's doing so that
it's obvious.

In the specific cases of the string formatting codes, they're a
special case that is a marginal win because of the large body of
existing experience with the standard C printf codes. That's weighed
against their considerable lack of readability; expand them to be
special for Python, and that "marginal win" is gone.

-- 
 \ "My girlfriend has a queen sized bed; I have a court jester |
  `\   sized bed. It's red and green and has bells on it, and the ends |
_o__)  curl up."  -- Steven Wright |
Ben Finney

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple string formatting question

2006-04-06 Thread Fredrik Lundh
Paul McGuire wrote:

> Ooops, don't combine the two calls to rstrip().
>
> def format(f, width=3): return ("%.*f" % (width, f)).rstrip(".0")
>
> print format(3.140)
> print format(3.000)
> print format(3.001)
> print format(30.)
> print format(30.000)

hey, I'm doing test-driven development.  being able to handle 30 and
30 wasn't part of the original spec ;-)

> But this works fine:
> def format(f, width=3): return ("%.*f" % (width, f)).rstrip("0").rstrip(".")

indeed.





-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple string formatting question

2006-04-07 Thread Peter Otten
Steven D'Aprano wrote:

> I have a sinking feeling I'm missing something really,
> really simple.
> 
> I'm looking for a format string similar to '%.3f'
> except that trailing zeroes are not included.
> 
> To give some examples:
> 
> FloatString
> 1.0  1
> 1.1  1.1
> 12.1234  12.123
> 12.0001  12
> 
> and similar.
> 
> Here is a (quick and dirty) reference implementation:
> 
> def format(f, width=3):
>  fs = '%%.%df' % width
>  s = fs % f
>  return s.rstrip('0').rstrip('.')
> 
> 
> Is there a way of getting the same result with just a
> single string format expression?

Does it have to be a string or can you cheat? If so:

>>> class Format(str):
... def __new__(cls, width):
... return str.__new__(cls, "%%.%df" % width)
... def __mod__(self, other):
... return str.__mod__(self, other).rstrip("0").rstrip(".")
...
>>> format = Format(3)
>>> for f in [1.0, 1.1, 12.1234, 12.0001]:
... print f, "-->", format % f
...
1.0 --> 1
1.1 --> 1.1
12.1234 --> 12.123
12.0001 --> 12

For passing around in your app that should be as convenient as a string --
of course it will break if you store the "format" in a file, say.

Peter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reverse string-formatting (maybe?)

2006-10-14 Thread Tim Chase
 template = 'I am %s, and he %s last %s.'
 values = ('coding', "coded', 'week')
 formatted = template % values
 formatted
> 'I am coding, and he coded last week.'
 deformat(formatted, template)
> ('coding', 'coded', 'week')
> 
> expanded (for better visual):
 deformat('I am coding, and he coded last week.', 'I am %s, and he %s last 
 %s.')
> ('coding', 'coded', 'week')
> 
> It would return a tuple of strings, since it has no way of telling what
> the original type of each item was.
> 
> Any input? I've looked through the documentation of the string module
> and re module, did a search of the documentation and a search of this
> group, and come up empty-handed.


Yes, in the trivial case you provide, it can be done fairly 
easily using the re module:

 >>> import re
 >>> template = 'I am %s, and he %s last %s.'
 >>> values = ('coding', 'coded', 'week')
 >>> formatted = template % values
 >>> unformat_re = re.escape(template).replace('%s', '(.*)')
 >>> # unformat_re = unformat_re.replace('%i', '([0-9]+)')
 >>> r = re.compile(unformat_re)
 >>> r.match(formatted).groups()
('coding', 'coded', 'week')

Thing's get crazier when you have things like

 >>> answer ='format values into a string'
 >>> template = 'The formatting string %%s is used to %s' % answer

or

 >>> template = 'The value is %0*.*f'
 >>> values = (10, 4, 3.14159)
 >>> formatted = template % values
 >>> formated
'The value is 3.1415'

or

 >>> template = 'Dear %(name)s, Thank you for the %(gift)s.  It 
was very %(adj).' % {'name': 'Grandma', 'gift': 'sweater', 'adj': 
'nice'}

Additionally, things go a little tangled when the replacement 
values duplicate matters in the template. Should the unformatting 
of "I am tired, and he didn't last last All Saint's Day" be 
parsed as ('tired', "didn't last", "All Saint's Day") or 
('tired', "didn't", "last All Saint's Day").  The /intent/ is 
likely the former, but getting a computer to understand intent is 
a non-trivial task ;)

Just a few early-morning thoughts...

-tkc






-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reverse string-formatting (maybe?)

2006-10-14 Thread Tim Chase
 template = 'I am %s, and he %s last %s.'
 values = ('coding', "coded', 'week')
 formatted = template % values
 formatted
> 'I am coding, and he coded last week.'
 deformat(formatted, template)
> ('coding', 'coded', 'week')
> 
> expanded (for better visual):
 deformat('I am coding, and he coded last week.', 'I am %s, and he %s last 
 %s.')
> ('coding', 'coded', 'week')
> 
> It would return a tuple of strings, since it has no way of telling what
> the original type of each item was.
> 
> Any input? I've looked through the documentation of the string module
> and re module, did a search of the documentation and a search of this
> group, and come up empty-handed.


Yes, in the trivial case you provide, it can be done fairly 
easily using the re module:

 >>> import re
 >>> template = 'I am %s, and he %s last %s.'
 >>> values = ('coding', 'coded', 'week')
 >>> formatted = template % values
 >>> unformat_re = re.escape(template).replace('%s', '(.*)')
 >>> # unformat_re = unformat_re.replace('%i', '([0-9]+)')
 >>> r = re.compile(unformat_re)
 >>> r.match(formatted).groups()
('coding', 'coded', 'week')

Thing's get crazier when you have things like

 >>> answer ='format values into a string'
 >>> template = 'The formatting string %%s is used to %s' % answer

or

 >>> template = 'The value is %0*.*f'
 >>> values = (10, 4, 3.14159)
 >>> formatted = template % values
 >>> formated
'The value is 3.1415'

or

 >>> template = 'Dear %(name)s, Thank you for the %(gift)s.  It 
was very %(adj).' % {'name': 'Grandma', 'gift': 'sweater', 'adj': 
'nice'}

Additionally, things go a little tangled when the replacement 
values duplicate matters in the template. Should the unformatting 
of "I am tired, and he didn't last last All Saint's Day" be 
parsed as ('tired', "didn't last", "All Saint's Day") or 
('tired', "didn't", "last All Saint's Day").  The /intent/ is 
likely the former, but getting a computer to understand intent is 
a non-trivial task ;)

Just a few early-morning thoughts...

-tkc






-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reverse string-formatting (maybe?)

2006-10-14 Thread Peter Otten
Dustan wrote:

> Is there any builtin function or module with a function similar to my
> made-up, not-written deformat function as follows? I can't imagine it
> would be too easy to write, but possible...
> 
 template = 'I am %s, and he %s last %s.'
 values = ('coding', "coded', 'week')
 formatted = template % values
 formatted
> 'I am coding, and he coded last week.'
 deformat(formatted, template)
> ('coding', 'coded', 'week')
> 
> expanded (for better visual):
 deformat('I am coding, and he coded last week.', 'I am %s, and he %s
 last %s.')
> ('coding', 'coded', 'week')
> 
> It would return a tuple of strings, since it has no way of telling what
> the original type of each item was.
> 
> 
> Any input? I've looked through the documentation of the string module
> and re module, did a search of the documentation and a search of this
> group, and come up empty-handed.

Simple, but unreliable:

>>> import re
>>> template = "I am %s, and he %s last %s."
>>> values = ("coding", "coded", "week")
>>> formatted = template % values
>>> def deformat(formatted, template):
... r = re.compile("(.*)".join(template.split("%s")))
... return r.match(formatted).groups()
...
>>> deformat(formatted, template)
('coding', 'coded', 'week')

Peter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reverse string-formatting (maybe?)

2006-10-15 Thread Dustan

Peter Otten wrote:
> Dustan wrote:
>
> > Is there any builtin function or module with a function similar to my
> > made-up, not-written deformat function as follows? I can't imagine it
> > would be too easy to write, but possible...
> >
>  template = 'I am %s, and he %s last %s.'
>  values = ('coding', "coded', 'week')
>  formatted = template % values
>  formatted
> > 'I am coding, and he coded last week.'
>  deformat(formatted, template)
> > ('coding', 'coded', 'week')
> >
> > expanded (for better visual):
>  deformat('I am coding, and he coded last week.', 'I am %s, and he %s
>  last %s.')
> > ('coding', 'coded', 'week')
> >
> > It would return a tuple of strings, since it has no way of telling what
> > the original type of each item was.
> >
> >
> > Any input? I've looked through the documentation of the string module
> > and re module, did a search of the documentation and a search of this
> > group, and come up empty-handed.
>
> Simple, but unreliable:
>
> >>> import re
> >>> template = "I am %s, and he %s last %s."
> >>> values = ("coding", "coded", "week")
> >>> formatted = template % values
> >>> def deformat(formatted, template):
> ... r = re.compile("(.*)".join(template.split("%s")))
> ... return r.match(formatted).groups()
> ...
> >>> deformat(formatted, template)
> ('coding', 'coded', 'week')
>
> Peter

Trying to figure out the 'unreliable' part of your statement...

I'm sure 2 '%s' characters in a row would be a bad idea, and if you
have similar expressions for the '%s' characters within as well as in
the neighborhood of the '%s', that would cause difficulty. Is there any
other reason it might not work properly?

My template outside of the '%s' characters contains only commas and
spaces, and within, neither commas nor spaces. Given that information,
is there any reason it might not work properly?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reverse string-formatting (maybe?)

2006-10-15 Thread Tim Chase
> My template outside of the '%s' characters contains only commas and
> spaces, and within, neither commas nor spaces. Given that information,
> is there any reason it might not work properly?

Given this new (key) information along with the assumption that 
you're doing straight string replacement (not dictionary 
replacement of the form "%(key)s" or other non-string types such 
as "%05.2f"), then yes, a reversal is possible.  To make it more 
explicit, one would do something like

 >>> template = '%s, %s, %s'
 >>> values = ('Tom', 'Dick', 'Harry')
 >>> formatted = template % values
 >>> import re
 >>> unformat_string = template.replace('%s', '([^, ]+)')
 >>> unformatter = re.compile(unformat_string)
 >>> extracted_values = unformatter.search(formatted).groups()

using '[^, ]+' to mean "one or more characters that aren't a 
comma or a space".

-tkc




-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reverse string-formatting (maybe?)

2006-10-15 Thread Dustan

Tim Chase wrote:
> > My template outside of the '%s' characters contains only commas and
> > spaces, and within, neither commas nor spaces. Given that information,
> > is there any reason it might not work properly?
>
> Given this new (key) information along with the assumption that
> you're doing straight string replacement (not dictionary
> replacement of the form "%(key)s" or other non-string types such
> as "%05.2f"), then yes, a reversal is possible.  To make it more
> explicit, one would do something like
>
>  >>> template = '%s, %s, %s'
>  >>> values = ('Tom', 'Dick', 'Harry')
>  >>> formatted = template % values
>  >>> import re
>  >>> unformat_string = template.replace('%s', '([^, ]+)')
>  >>> unformatter = re.compile(unformat_string)
>  >>> extracted_values = unformatter.search(formatted).groups()
>
> using '[^, ]+' to mean "one or more characters that aren't a
> comma or a space".
>
> -tkc

Thanks.

One more thing (I forgot to mention this other situation earlier)
The %s characters are ints, and outside can be anything except int
characters. I do have one situation of '%s%s%s', but I can change it to
'%s', and change the output into the needed output, so that's not
important. Think something along the lines of "abckdaldj iweo%s
qwierxcnv !%sjd".

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reverse string-formatting (maybe?)

2006-10-15 Thread Dustan

Dustan wrote:
> Tim Chase wrote:
> > > My template outside of the '%s' characters contains only commas and
> > > spaces, and within, neither commas nor spaces. Given that information,
> > > is there any reason it might not work properly?
> >
> > Given this new (key) information along with the assumption that
> > you're doing straight string replacement (not dictionary
> > replacement of the form "%(key)s" or other non-string types such
> > as "%05.2f"), then yes, a reversal is possible.  To make it more
> > explicit, one would do something like
> >
> >  >>> template = '%s, %s, %s'
> >  >>> values = ('Tom', 'Dick', 'Harry')
> >  >>> formatted = template % values
> >  >>> import re
> >  >>> unformat_string = template.replace('%s', '([^, ]+)')
> >  >>> unformatter = re.compile(unformat_string)
> >  >>> extracted_values = unformatter.search(formatted).groups()
> >
> > using '[^, ]+' to mean "one or more characters that aren't a
> > comma or a space".
> >
> > -tkc
>
> Thanks.
>
> One more thing (I forgot to mention this other situation earlier)
> The %s characters are ints, and outside can be anything except int
> characters. I do have one situation of '%s%s%s', but I can change it to
> '%s', and change the output into the needed output, so that's not
> important. Think something along the lines of "abckdaldj iweo%s
> qwierxcnv !%sjd".

That was written in haste. All the information is true. The question:
I've already created a function to do this, using your original
deformat function. Is there any way in which it might go wrong?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reverse string-formatting (maybe?)

2006-10-15 Thread Dustan

Dustan wrote:
> Dustan wrote:
> > Tim Chase wrote:
> > > > My template outside of the '%s' characters contains only commas and
> > > > spaces, and within, neither commas nor spaces. Given that information,
> > > > is there any reason it might not work properly?
> > >
> > > Given this new (key) information along with the assumption that
> > > you're doing straight string replacement (not dictionary
> > > replacement of the form "%(key)s" or other non-string types such
> > > as "%05.2f"), then yes, a reversal is possible.  To make it more
> > > explicit, one would do something like
> > >
> > >  >>> template = '%s, %s, %s'
> > >  >>> values = ('Tom', 'Dick', 'Harry')
> > >  >>> formatted = template % values
> > >  >>> import re
> > >  >>> unformat_string = template.replace('%s', '([^, ]+)')
> > >  >>> unformatter = re.compile(unformat_string)
> > >  >>> extracted_values = unformatter.search(formatted).groups()
> > >
> > > using '[^, ]+' to mean "one or more characters that aren't a
> > > comma or a space".
> > >
> > > -tkc
> >
> > Thanks.
> >
> > One more thing (I forgot to mention this other situation earlier)
> > The %s characters are ints, and outside can be anything except int
> > characters. I do have one situation of '%s%s%s', but I can change it to
> > '%s', and change the output into the needed output, so that's not
> > important. Think something along the lines of "abckdaldj iweo%s
> > qwierxcnv !%sjd".
>
> That was written in haste. All the information is true. The question:
> I've already created a function to do this, using your original
> deformat function. Is there any way in which it might go wrong?

Again, haste. I used Peter's deformat function.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reverse string-formatting (maybe?)

2006-10-15 Thread Dan Sommers
On 14 Oct 2006 05:35:02 -0700,
"Dustan" <[EMAIL PROTECTED]> wrote:

> Is there any builtin function or module with a function similar to my
> made-up, not-written deformat function as follows? I can't imagine it
> would be too easy to write, but possible...

[ snip ]

> Any input? I've looked through the documentation of the string module
> and re module, did a search of the documentation and a search of this
> group, and come up empty-handed.

Track down pyscanf.  (Google is your friend, but I can't find any sort
of licensing/copyright information, and the web addresses in the source
code aren't available, so I hesitate to post my ancient copy.)

HTH,
Dan

-- 
Dan Sommers

"I wish people would die in alphabetical order." -- My wife, the genealogist
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reverse string-formatting (maybe?)

2006-10-15 Thread Tim Chase
>>>  >>> template = '%s, %s, %s'
>>>  >>> values = ('Tom', 'Dick', 'Harry')
>>>  >>> formatted = template % values
>>>  >>> import re
>>>  >>> unformat_string = template.replace('%s', '([^, ]+)')
>>>  >>> unformatter = re.compile(unformat_string)
>>>  >>> extracted_values = unformatter.search(formatted).groups()
>>>
>>> using '[^, ]+' to mean "one or more characters that aren't a
>>> comma or a space".
>>
>> One more thing (I forgot to mention this other situation earlier)
>> The %s characters are ints, and outside can be anything except int
>> characters. I do have one situation of '%s%s%s', but I can change it to
>> '%s', and change the output into the needed output, so that's not
>> important. Think something along the lines of "abckdaldj iweo%s
>> qwierxcnv !%sjd".
> 
> That was written in haste. All the information is true. The question:
> I've already created a function to do this, using your original
> deformat function. Is there any way in which it might go wrong?

Only you know what anomalies will be found in your data-sets.  If 
you know/assert that

-the only stuff in the formatting string is one set of characters

-that stuff in the replacement-values can never include any of 
your format-string characters

-that you're not using funky characters/formatting in your format 
string (such as "%%" possibly followed by an "s" to get the 
resulting text of "%s" after formatting, or trying to use other 
formatters such as the aforementioned "%f" or possibly "%i")

then you should be safe.  It could also be possible (with my 
original replacement of "(.*)") if your values will never include 
any substring of your format string.  If you can't guarantee 
these conditions, you're trying to make a cow out of hamburger. 
Or a pig out of sausage.  Or a whatever out of a hotdog. :)

Conventional wisdom would tell you to create a test-suite of 
format-strings and sample values (preferably worst-case funkiness 
in your expected format-strings/values), and then have a test 
function that will assert that the unformatting of every 
formatted string in the set returns the same set of values that 
went in.  Something like

tests = {
'I was %s but now I am %s' : [
('hot', 'cold'),
('young', 'old'),
],
'He has 3 %s and 2 %s' : [
('brothers', 'sisters'),
('cats', 'dogs')
]
}

for format_string, values in tests:
unformatter = format.replace('%s', '(.*)')
for value_tuple in values:
formatted = format_string % value_tuple
unformatted = unformatter.search(formatted).groups()
if unformatted <> value_tuple:
print "%s doesn't match %s when unformatting %s" % (
unformatted,
value_tuple
format_string)

-tkc








-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reverse string-formatting (maybe?)

2006-10-15 Thread Dustan

> Only you know what anomalies will be found in your data-sets.  If
> you know/assert that
>
> -the only stuff in the formatting string is one set of characters
>
> -that stuff in the replacement-values can never include any of
> your format-string characters
>
> -that you're not using funky characters/formatting in your format
> string (such as "%%" possibly followed by an "s" to get the
> resulting text of "%s" after formatting, or trying to use other
> formatters such as the aforementioned "%f" or possibly "%i")
>
> then you should be safe.  It could also be possible (with my
> original replacement of "(.*)") if your values will never include
> any substring of your format string.  If you can't guarantee
> these conditions, you're trying to make a cow out of hamburger.
> Or a pig out of sausage.  Or a whatever out of a hotdog. :)
>
> Conventional wisdom would tell you to create a test-suite of
> format-strings and sample values (preferably worst-case funkiness
> in your expected format-strings/values), and then have a test
> function that will assert that the unformatting of every
> formatted string in the set returns the same set of values that
> went in.  Something like
>
> tests = {
>   'I was %s but now I am %s' : [
>   ('hot', 'cold'),
>   ('young', 'old'),
>   ],
>   'He has 3 %s and 2 %s' : [
>   ('brothers', 'sisters'),
>   ('cats', 'dogs')
>   ]
>   }
>
> for format_string, values in tests:
>   unformatter = format.replace('%s', '(.*)')
>   for value_tuple in values:
>   formatted = format_string % value_tuple
>   unformatted = unformatter.search(formatted).groups()
>   if unformatted <> value_tuple:
>   print "%s doesn't match %s when unformatting %s" % (
>   unformatted,
>   value_tuple
>   format_string)
> 
> -tkc

Thanks for all your help. I've gotten the idea.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: string formatting: engineering notation

2007-03-14 Thread Steve Holden
Darren Dale wrote:
> Does anyone know if it is possible to represent a number as a string with
> engineering notation (like scientific notation, but with 10 raised to
> multiples of 3: 120e3, 12e-6, etc.). I know this is possible with the
> decimal.Decimal class, but repeatedly instantiating Decimals is inefficient
> for my application (matplotlib plotting library). If it is not currently
> possible, do you think the python devs would be receptive to including
> support for engineering notation in future releases?
> 
How close is this:

  >>> "%.3e" % 3.14159
'3.142e+00'

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note:  http://holdenweb.blogspot.com
See you at PyCon? http://us.pycon.org/TX2007

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: string formatting: engineering notation

2007-03-14 Thread Darren Dale
Steve Holden wrote:

> Darren Dale wrote:
>> Does anyone know if it is possible to represent a number as a string with
>> engineering notation (like scientific notation, but with 10 raised to
>> multiples of 3: 120e3, 12e-6, etc.). I know this is possible with the
>> decimal.Decimal class, but repeatedly instantiating Decimals is
>> inefficient for my application (matplotlib plotting library). If it is
>> not currently possible, do you think the python devs would be receptive
>> to including support for engineering notation in future releases?
>> 
> How close is this:
> 
>   >>> "%.3e" % 3.14159
> '3.142e+00'

>>> "%.3e" % 31415.9
'3.142e+04'

What I am looking for is '31.4159e+03'

Darren

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: string formatting: engineering notation

2007-03-14 Thread Grant Edwards
On 2007-03-14, Steve Holden <[EMAIL PROTECTED]> wrote:
> Darren Dale wrote:
>> Does anyone know if it is possible to represent a number as a string with
>> engineering notation (like scientific notation, but with 10 raised to
>> multiples of 3: 120e3, 12e-6, etc.). I know this is possible with the
>> decimal.Decimal class, but repeatedly instantiating Decimals is inefficient
>> for my application (matplotlib plotting library). If it is not currently
>> possible, do you think the python devs would be receptive to including
>> support for engineering notation in future releases?
>> 
> How close is this:
>
>  >>> "%.3e" % 3.14159
> '3.142e+00'

Not close at all. It should be "3.14159"

>>> "%.3e" % 31.4159
'3.142e+01'

should be 31.4159

>>> "%.3e" % 314.159
'3.142e+02'

should be 314.159

>>> "%.3e" % 31415.9
'3.142e+04'

should be 31.4159e3

-- 
Grant Edwards   grante Yow!  LOU GRANT froze
  at   my ASSETS!!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: string formatting: engineering notation

2007-03-14 Thread Jorge Godoy
Steve Holden <[EMAIL PROTECTED]> writes:

> Darren Dale wrote:
>> Does anyone know if it is possible to represent a number as a string with
>> engineering notation (like scientific notation, but with 10 raised to
>> multiples of 3: 120e3, 12e-6, etc.). I know this is possible with the
>> decimal.Decimal class, but repeatedly instantiating Decimals is inefficient
>> for my application (matplotlib plotting library). If it is not currently
>> possible, do you think the python devs would be receptive to including
>> support for engineering notation in future releases?
>>
> How close is this:
>
>  >>> "%.3e" % 3.14159
> '3.142e+00'

>>> "%.3e" % 314159
'3.142e+05'
>>> 

Not close when you have the exponent.  



-- 
Jorge Godoy  <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: string formatting: engineering notation

2007-03-14 Thread attn . steven . kuo
On Mar 14, 1:14 pm, Darren Dale <[EMAIL PROTECTED]> wrote:
> Does anyone know if it is possible to represent a number as a string with
> engineering notation (like scientific notation, but with 10 raised to
> multiples of 3: 120e3, 12e-6, etc.). I know this is possible with the
> decimal.Decimal class, but repeatedly instantiating Decimals is inefficient
> for my application (matplotlib plotting library). If it is not currently
> possible, do you think the python devs would be receptive to including
> support for engineering notation in future releases?


Do you also consider this to be too inefficient?


import math

for exponent in xrange(-10, 11):
flt = 1.23 * math.pow(10, exponent)
l = math.log10(flt)
if l < 0:
l = l - 3
p3 = int(l / 3) * 3
multiplier = flt / pow(10, p3)
print '%e => %fe%d' % (flt, multiplier, p3)

--
Hope this helps,
Steven

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: string formatting: engineering notation

2007-03-14 Thread Darren Dale
[EMAIL PROTECTED] wrote:

> On Mar 14, 1:14 pm, Darren Dale <[EMAIL PROTECTED]> wrote:
>> Does anyone know if it is possible to represent a number as a string with
>> engineering notation (like scientific notation, but with 10 raised to
>> multiples of 3: 120e3, 12e-6, etc.). I know this is possible with the
>> decimal.Decimal class, but repeatedly instantiating Decimals is
>> inefficient for my application (matplotlib plotting library). If it is
>> not currently possible, do you think the python devs would be receptive
>> to including support for engineering notation in future releases?
> 
> 
> Do you also consider this to be too inefficient?
> 
> 
> import math
> 
> for exponent in xrange(-10, 11):
> flt = 1.23 * math.pow(10, exponent)
> l = math.log10(flt)
> if l < 0:
> l = l - 3
> p3 = int(l / 3) * 3
> multiplier = flt / pow(10, p3)
> print '%e => %fe%d' % (flt, multiplier, p3)
> 

That's a good suggestion. It's probably fast enough. I was hoping that
something like '%n'%my_number already existed.
-- 
http://mail.python.org/mailman/listinfo/python-list


String formatting with fixed width

2007-03-16 Thread Alexander Eisenhuth
Hello alltogether,

is it possible to format stings with fixed width of let's say 7 character. T 
need a floating point with 3 chars before dot, padded with ' ' and 3 chars 
after 
dot, padded with '0'.

Followingh is my approach
 >>> f = 21.1
 >>> s = "%.03f" % f
 >>> s
'21.100'

But there are missing ' '. How can I get that? (For bigger numbers than 999 
they 
might be cut: 1021 -> 021)

Alexander
-- 
http://mail.python.org/mailman/listinfo/python-list


String formatting with fixed width

2007-03-16 Thread Alexander Eisenhuth
Hello alltogether,

is it possible to format stings with fixed width of let's say 7 character. T 
need a floating point with 3 chars before dot, padded with ' ' and 3 chars 
after 
dot, padded with '0'.

Followingh is my approach
 >>> f = 21.1
 >>> s = "%.03f" % f
 >>> s
'21.100'

But there are missing ' '. How can I get that? (For bigger numbers than 999 
they 
might be cut: 1021 -> 021)

Thanks,
Alexander
-- 
http://mail.python.org/mailman/listinfo/python-list


String formatting with nested dictionaries

2006-08-24 Thread [EMAIL PROTECTED]
I've got a bit of code which has a dictionary nested within another
dictionary.  I'm trying to print out specific values from the inner
dict in a formatted string and I'm running into a roadblock.  I can't
figure out how to get a value from the inner dict into the string.  To
make this even more complicated this is being compiled into a large
string including other parts of the outer dict.

mydict = {'inner_dict':{'Value1':1, 'Value2':2}, 'foo':'bar',
'Hammer':'nails'}

print "foo is set to %(foo)s - Value One is: %(inner_dict['Value1'])s
and Value Two is: %(inner_dict['Value2'])s -- Hammers are used to pound
in %(Hammer)s" % mydict

The above fails looking for a key named 'inner_dict['Value1']' which
doesn't exist.

I've looked through the docs and google and can't find anything
relating to this.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: string formatting using the % operator

2005-06-13 Thread fargo
William Gill wrote:
> I am using the % operator to create queries for a db app.  It works fine 
> when exact strings, or numbers are used, but some queries need partial 
> matching that use the '%' as a wildcards. So for example the resultant 
> string should be 'WHERE name LIKE %smith%'  (would match silversmith, 
> smithy, and smith).  Is there any way to get something like
> 
>   searchterm = 'smith'
>   sql += 'WHERE name LIKE %s'  %  searchterm
> 
> to return 'WHERE name LIKE %smith%'I have tried using escapes, 
> character codes for the % sign, and lots of other gyrations with no 
> success.  The only thing that works is if I modify searchterm first:
> 
>   searchterm = 'smith'
>   searchterm ='%'+'smith'+'%'
>   sql += 'WHERE name LIKE %s'  %  searchterm
> 
> Any Ideas?
try this :

sql += 'WHERE name LIKE %%%s%%'  %  searchterm
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: string formatting using the % operator

2005-06-13 Thread harold fellermann
> to return 'WHERE name LIKE %smith%'I have tried using escapes,
> character codes for the % sign, and lots of other gyrations with no
> success.  The only thing that works is if I modify searchterm first:
>
>searchterm = 'smith'
>searchterm ='%'+'smith'+'%'
>sql += 'WHERE name LIKE %s'  %  searchterm
>
> Any Ideas?

 >>> "%%%s%%" % "here you go"
'%here you go%'

Cheers,

- harold -

--
If your only tool is a hammer, every problem looks like a nail.
--

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: string formatting using the % operator

2005-06-13 Thread Dan Sommers
On Mon, 13 Jun 2005 15:12:54 GMT,
William Gill <[EMAIL PROTECTED]> wrote:

> I am using the % operator to create queries for a db app.  It works fine
> when exact strings, or numbers are used, but some queries need partial
> matching that use the '%' as a wildcards. So for example the resultant
> string should be 'WHERE name LIKE %smith%'  (would match silversmith,
> smithy, and smith).  Is there any way to get something like

>searchterm = 'smith'
>sql += 'WHERE name LIKE %s'  %  searchterm

> to return 'WHERE name LIKE %smith%'I have tried using escapes,
> character codes for the % sign, and lots of other gyrations with no
> success.  The only thing that works is if I modify searchterm first:

>searchterm = 'smith'
>searchterm ='%'+'smith'+'%'
>sql += 'WHERE name LIKE %s'  %  searchterm

> Any Ideas?

Let the DB-API do more work for you:

cursor = connection.cursor( )
sql = """SELECT column2, columns3 FROM table WHERE name LIKE %s"""
values = ('%%%s%%' % searchterm,) # note that this is a tuple
cursor.execute( sql, values )

HTH,
Dan

-- 
Dan Sommers

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: string formatting using the % operator

2005-06-13 Thread William Gill
Dan Sommers wrote:
> On Mon, 13 Jun 2005 15:12:54 GMT,
> William Gill <[EMAIL PROTECTED]> wrote:
> 
> 
>>I am using the % operator to create queries for a db app.  It works fine
>>when exact strings, or numbers are used, but some queries need partial
>>matching that use the '%' as a wildcards. So for example the resultant
>>string should be 'WHERE name LIKE %smith%'  (would match silversmith,
>>smithy, and smith).  Is there any way to get something like
> 
> 
>>   searchterm = 'smith'
>>   sql += 'WHERE name LIKE %s'  %  searchterm
> 
> 
>>to return 'WHERE name LIKE %smith%'I have tried using escapes,
>>character codes for the % sign, and lots of other gyrations with no
>>success.  The only thing that works is if I modify searchterm first:
> 
> 
>>   searchterm = 'smith'
>>   searchterm ='%'+'smith'+'%'
>>   sql += 'WHERE name LIKE %s'  %  searchterm
> 
> 
>>Any Ideas?
> 
> 
> Let the DB-API do more work for you:
> 
> cursor = connection.cursor( )
> sql = """SELECT column2, columns3 FROM table WHERE name LIKE %s"""
> values = ('%%%s%%' % searchterm,) # note that this is a tuple
> cursor.execute( sql, values )
> 
> HTH,
> Dan
> 

I can't tell you how many times I looked at the table of format codes 
and missed this.

Thanks everyone!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: string formatting using the % operator

2005-06-13 Thread Peter Hansen
Dan Sommers wrote:
> Let the DB-API do more work for you:
> 
> cursor = connection.cursor( )
> sql = """SELECT column2, columns3 FROM table WHERE name LIKE %s"""
> values = ('%%%s%%' % searchterm,) # note that this is a tuple

It looks like this might be a rare case where not using the % operator 
might make it easier to see what's going on:

   values = ('%' + searchterm + '%',)

-Peter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String formatting with fixed width

2007-03-16 Thread Steve Holden
Alexander Eisenhuth wrote:
> Hello alltogether,
> 
> is it possible to format stings with fixed width of let's say 7 character. T 
> need a floating point with 3 chars before dot, padded with ' ' and 3 chars 
> after 
> dot, padded with '0'.
> 
> Followingh is my approach
>  >>> f = 21.1
>  >>> s = "%.03f" % f
>  >>> s
> '21.100'
> 
> But there are missing ' '. How can I get that? (For bigger numbers than 999 
> they 
> might be cut: 1021 -> 021)
> 
  >>> def f(x):
  ...   return "%7.3f" % (x % 1000.0)
  ...
  >>> for x in (9.9, 99.9, 999.9, .9):
  ...   print f(x)
  ...
   9.900
  99.900
999.900
999.900
  >>>

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note:  http://holdenweb.blogspot.com
See you at PyCon? http://us.pycon.org/TX2007

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String formatting with fixed width

2007-03-16 Thread Jon Clements
On 16 Mar, 13:20, Alexander Eisenhuth <[EMAIL PROTECTED]>
wrote:
> Hello alltogether,
>
> is it possible to format stings with fixed width of let's say 7 character. T
> need a floating point with 3 chars before dot, padded with ' ' and 3 chars 
> after
> dot, padded with '0'.
>
> Followingh is my approach
>  >>> f = 21.1
>  >>> s = "%.03f" % f
>  >>> s
> '21.100'
>
> But there are missing ' '. How can I get that? (For bigger numbers than 999 
> they
> might be cut: 1021 -> 021)

You can use something like this:
>> print '%7.03f' % 21.1
' 21.100'


However, this will only make the string at *least* 7 long. If the
length of the number exceeds this, you'll end up with it even longer;
for instance:

>> print '%7.03f' % 2123123121.1
'2123123121.100'

>From your example about 'cutting' it, it looks like you just might be
able to take the last 7 chars from it using [-7:]

hth

Jon.






-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String formatting with fixed width

2007-03-16 Thread Steve Holden
Steve Holden wrote:
> Alexander Eisenhuth wrote:
>> Hello alltogether,
>>
>> is it possible to format stings with fixed width of let's say 7 character. T 
>> need a floating point with 3 chars before dot, padded with ' ' and 3 chars 
>> after 
>> dot, padded with '0'.
>>
>> Followingh is my approach
>>  >>> f = 21.1
>>  >>> s = "%.03f" % f
>>  >>> s
>> '21.100'
>>
>> But there are missing ' '. How can I get that? (For bigger numbers than 999 
>> they 
>> might be cut: 1021 -> 021)
>>
>   >>> def f(x):
>   ...   return "%7.3f" % (x % 1000.0)
>   ...
>   >>> for x in (9.9, 99.9, 999.9, .9):
>   ...   print f(x)
>   ...
>9.900
>   99.900
> 999.900
> 999.900
>   >>>
> 
... but (unfortunately?):

  >>> f(-.99)
'  0.010'
  >>>

You don't say what you want to do about negative numbers, so this may or 
may not be significant.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note:  http://holdenweb.blogspot.com
See you at PyCon? http://us.pycon.org/TX2007

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String formatting with fixed width

2007-03-16 Thread Alexander Eisenhuth
Thanks for your fast reply. I'm fine with your "%7.03f" solution. (negatives 
are 
  not significant)

Alexander Eisenhuth schrieb:
> Hello alltogether,
> 
> is it possible to format stings with fixed width of let's say 7 
> character. T need a floating point with 3 chars before dot, padded with 
> ' ' and 3 chars after dot, padded with '0'.
> 
> Followingh is my approach
>  >>> f = 21.1
>  >>> s = "%.03f" % f
>  >>> s
> '21.100'
> 
> But there are missing ' '. How can I get that? (For bigger numbers than 
> 999 they might be cut: 1021 -> 021)
> 
> Thanks,
> Alexander
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String formatting with nested dictionaries

2006-08-24 Thread Diez B. Roggisch
[EMAIL PROTECTED] schrieb:
> I've got a bit of code which has a dictionary nested within another
> dictionary.  I'm trying to print out specific values from the inner
> dict in a formatted string and I'm running into a roadblock.  I can't
> figure out how to get a value from the inner dict into the string.  To
> make this even more complicated this is being compiled into a large
> string including other parts of the outer dict.
> 
> mydict = {'inner_dict':{'Value1':1, 'Value2':2}, 'foo':'bar',
> 'Hammer':'nails'}
> 
> print "foo is set to %(foo)s - Value One is: %(inner_dict['Value1'])s
> and Value Two is: %(inner_dict['Value2'])s -- Hammers are used to pound
> in %(Hammer)s" % mydict
> 
> The above fails looking for a key named 'inner_dict['Value1']' which
> doesn't exist.
> 
> I've looked through the docs and google and can't find anything
> relating to this.

Because it is not supported. You can only use one level of keys, and it 
must be strings. So you have to do it like this:


print "foo is set to %(foo)s - Value One is: %(inner_dict['Value1'])s 
and Value Two is: %(inner_dict['Value2'])s -- Hammers are used to 
poundin %(Hammer)s" % dict(Hammer=mydict['Hammer'], 
Value1=mydict["inner_dict"]["Value1"], 
Value2=mydict["inner_dict"]["Value2"])


Diez

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String formatting with nested dictionaries

2006-08-24 Thread Gabriel Genellina

At Thursday 24/8/2006 13:22, [EMAIL PROTECTED] wrote:


I've got a bit of code which has a dictionary nested within another
dictionary.  I'm trying to print out specific values from the inner
dict in a formatted string and I'm running into a roadblock.  I can't
figure out how to get a value from the inner dict into the string.  To
make this even more complicated this is being compiled into a large
string including other parts of the outer dict.

mydict = {'inner_dict':{'Value1':1, 'Value2':2}, 'foo':'bar',
'Hammer':'nails'}

print "foo is set to %(foo)s - Value One is: %(inner_dict['Value1'])s
and Value Two is: %(inner_dict['Value2'])s -- Hammers are used to pound
in %(Hammer)s" % mydict

The above fails looking for a key named 'inner_dict['Value1']' which
doesn't exist.


I can think of two ways:

a) Flatten your dictionary. That is, move the contents of inner_dict 
onto the outer dict:

mydict.update(mydict['inner_dict'])
Then use single names for interpolation

b) Do the interpolation in two steps.

template = "foo is set to %(foo)s - Value One is: %(Value1)s
and Value Two is: %(Value2)s -- Hammers are used to pound
in %(Hammer)s"
output = template % mydict['inner_dict']
output = output % mydict

Both methods assume that the inner dict takes precedence in case of 
name clashes; reverse the order if you want the opposite.



Gabriel Genellina
Softlab SRL 






__
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas


-- 
http://mail.python.org/mailman/listinfo/python-list

Re: String formatting with nested dictionaries

2006-08-24 Thread [EMAIL PROTECTED]

Gabriel Genellina wrote:
> At Thursday 24/8/2006 13:22, [EMAIL PROTECTED] wrote:
>
> >I've got a bit of code which has a dictionary nested within another
> >dictionary.  I'm trying to print out specific values from the inner
> >dict in a formatted string and I'm running into a roadblock.  I can't
> >figure out how to get a value from the inner dict into the string.  To
> >make this even more complicated this is being compiled into a large
> >string including other parts of the outer dict.
> >
> >mydict = {'inner_dict':{'Value1':1, 'Value2':2}, 'foo':'bar',
> >'Hammer':'nails'}
> >
> >print "foo is set to %(foo)s - Value One is: %(inner_dict['Value1'])s
> >and Value Two is: %(inner_dict['Value2'])s -- Hammers are used to pound
> >in %(Hammer)s" % mydict
> >
> >The above fails looking for a key named 'inner_dict['Value1']' which
> >doesn't exist.
>
> I can think of two ways:
>
> a) Flatten your dictionary. That is, move the contents of inner_dict
> onto the outer dict:
> mydict.update(mydict['inner_dict'])
> Then use single names for interpolation
>
> b) Do the interpolation in two steps.
>
> template = "foo is set to %(foo)s - Value One is: %(Value1)s
> and Value Two is: %(Value2)s -- Hammers are used to pound
> in %(Hammer)s"
> output = template % mydict['inner_dict']
> output = output % mydict
>
> Both methods assume that the inner dict takes precedence in case of
> name clashes; reverse the order if you want the opposite.
>
>
> Gabriel Genellina
> Softlab SRL
>

Thanks,  I started going with a) only doing it the long way.
(mydict['Value1'] = mydict['inner_dict']['Value1'])  mydict.update() is
*much* simpler and less prone to errors too.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String formatting with nested dictionaries

2006-08-24 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> I've got a bit of code which has a dictionary nested within another
> dictionary.  I'm trying to print out specific values from the inner
> dict in a formatted string and I'm running into a roadblock.  I can't
> figure out how to get a value from the inner dict into the string.  To
> make this even more complicated this is being compiled into a large
> string including other parts of the outer dict.
> 
> mydict = {'inner_dict':{'Value1':1, 'Value2':2}, 'foo':'bar',
> 'Hammer':'nails'}
> 
> print "foo is set to %(foo)s - Value One is: %(inner_dict['Value1'])s
> and Value Two is: %(inner_dict['Value2'])s -- Hammers are used to pound
> in %(Hammer)s" % mydict
> 
> The above fails looking for a key named 'inner_dict['Value1']' which
> doesn't exist.

the % operator treats the keys as plain keys, not expressions.  if you 
trust the template provider, you can use a custom wrapper to evaluate 
the key expressions:

mydict = {'inner_dict':{'Value1':1, 'Value2':2}, 'foo':'bar', 
'Hammer':'nails'}

class wrapper:
 def __init__(self, dict):
self.dict = dict
 def __getitem__(self, key):
try:
return self.dict[key]
except KeyError:
return eval(key, self.dict)

print "foo is set to %(foo)s - Value One is: %(inner_dict['Value1'])s 
and Value Two is: %(inner_dict['Value2'])s -- Hammers are used to pound 
in %(Hammer)s" % wrapper(mydict)

foo is set to bar - Value One is: 1 and Value Two is: 2 -- Hammers are 
used to pound in nails



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String formatting with nested dictionaries

2006-08-24 Thread Maric Michaud
Le jeudi 24 août 2006 21:02, Fredrik Lundh a écrit :
> class wrapper:
>      def __init__(self, dict):
> self.dict = dict
>      def __getitem__(self, key):
> try:
>     return self.dict[key]
> except KeyError:
>    

Quite the same idea, but without eval and the need to know the internal dict 
arborescence :

In [242]: class nested_dict_wrapper :
   .: def __init__(self, dic) :
   .: self._all = [dic] + [nested_dict_wrapper(v) for v in 
dic.values() if isinstance(v, dict)]
   .: def __getitem__(self, v) :
   .: for i in self._all :
   .: try : return i[v]
   .: except KeyError: pass
   .: raise KeyError(v + ' not found in dict and subdicts')
   .:
   .:

In [248]: complex_dict = { '0': 'zero', '1':'one', 'in1' : {'2':'two'}, 'in2':
{'3': 'three', '4' :'four', 'deeper':{'5':'five', '6':'six'}}, '7':'seven' }

In [250]: "%%(%s)s "*7 % tuple(range(7)) % nested_dict_wrapper(complex_dict)
Out[250]: 'zero one two three four five six '

In [251]: "%%(%s)s "*8 % tuple(range(8)) % nested_dict_wrapper(complex_dict)
Out[251]: 'zero one two three four five six seven '

In [252]: "%%(%s)s "*9 % tuple(range(9)) % nested_dict_wrapper(complex_dict)
---
exceptions.KeyError  Traceback (most recent 
call last)

/home/maric/

/home/maric/ in __getitem__(self, v)

KeyError: '8 not found in dict and subdicts'


-- 
_

Maric Michaud
_

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter Listbox string formatting question - how to kill adancingsnake ?

2006-10-31 Thread Hendrik van Rooyen
"Hendrik van Rooyen" <[EMAIL PROTECTED]> wrote:

> "Fredrik Lundh" <[EMAIL PROTECTED]> wrote:
>
> > instead of trying to force the listbox to behave like a multicolumn
> > widget, maybe you could switch to another widget?  some alternatives include
> >
> >  a Text widget (you have to roll your own selection logic)
>
> I _really_ don't feel strong enough for this, or for sticking them loose on a
> canvas...
8<

sorry - thought has just occurred to me - my basic problem is text formatting,
as variable width fonts make it difficult to get two things to line up under one
another by using spaces as padding  - so how would the Text widget have
helped me with this ?  or - Luxury ! - can I set a tab stop in pixels ?
- maybe I can catch a general clue here...

- Hendrik


-- 
http://mail.python.org/mailman/listinfo/python-list


MySQLDB - parameterised SQL - "TypeError: not all arguments converted during string formatting"

2006-02-19 Thread shearichard
Hi - I have written some python to insert a row into a table using
MySQLDB. I have never before written SQL/Python using embedded
parameters in the SQL and I'm having some difficulties. Could someone
point me in the right direction please ?

The python looks like this :

import MySQLdb
import MySQLdb.cursors
conn = MySQLdb.Connect(host='localhost', user='abc,passwd='def',
db='ghi',compress=1)

cursor = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)
sqlQuery = "INSERT INTO EVA_COMPANY
(COM_ADDRESS,COM_AUTOID,COM_COMPANY_ADDRESS,COM_STRUCT_OWNER_CODE)
VALUES (?,?,?,?) "
print sqlQuery
sql = cursor.execute(sqlQuery,("test","NULL","Tester1017",5))
cursor.close()
conn.commit()

... and the table looks like this ...

CREATE TABLE `eva_company` (
  `COM_AUTOID` int(9) unsigned NOT NULL auto_increment,
  `COM_COMPANY_NAME` varchar(128) NOT NULL,
  `COM_TRADING_NAME` varchar(128) default NULL,
  `COM_ADDRESS` varchar(256) NOT NULL,
  `COM_POSTAL_ADDRESS` varchar(256) default NULL,
  `COM_CONTACT_NAME` varchar(56) default NULL,
  `COM_CONTACT_POSITION` varchar(56) default NULL,
  `COM_CONTACT_TELEPHONE` varchar(16) default NULL,
  `COM_CONTACT_FAX` varchar(16) default NULL,
  `COM_CONTACT_EMAIL` varchar(256) default NULL,
  `COM_STRUCT_OWNER_CODE` int(9) unsigned default NULL,
  `COM_INDUSTRY_CODE` varchar(16) default NULL,
  `COM_INDUSTRY_DESC` varchar(56) default NULL,
  `COM_NUMBER_OF_SITES` int(9) default NULL,
  `COM_NATURE_OF_RELATIONSHIP` varchar(128) default NULL,
  PRIMARY KEY  (`COM_AUTOID`),
  KEY `IDX_COM1` (`COM_STRUCT_OWNER_CODE`),
  KEY `IDX_COM0` (`COM_COMPANY_NAME`),
  CONSTRAINT `FK_COS_COM0` FOREIGN KEY (`COM_STRUCT_OWNER_CODE`)
REFERENCES `eva_code_comp_struct_ownership` (`COS_AUTOID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;

... but when I try to execute the python I get an error ...

Traceback (most recent call last):
  File "sheadbtest1.py", line 8, in ?
sql = cursor.execute(sqlQuery,("test","NULL","Tester1017",5))
  File
"C:\bin\installed\Python2.4.1\Lib\site-packages\MySQLdb\cursors.py",
line 132, in execute
self.errorhandler(self, TypeError, m)
  File
"C:\bin\installed\Python2.4.1\Lib\site-packages\MySQLdb\connections.py",
line 33, in defaulterrorhandler
raise errorclass, errorvalue
TypeError: not all arguments converted during string formatting

... as I say if anyone could provide me with some tips I'd appreciate
it.

thanks

richard shea.

-- 
http://mail.python.org/mailman/listinfo/python-list


Tkinter Listbox string formatting question - how to kill a dancing snake ?

2006-10-30 Thread Hendrik van Rooyen
I am populating a listbox from a directory that looks like this:

variable_dict = {"funny_long_or_short_variable_name_as_key": (2,45),..

the tuple represents a "card, line" pair.
medf is a font object and a forward reference here.

I write:

for x in variable_dict:
txt = x
while medf.measure(txt) < 350:
txt = txt + ' '
txt = txt + str(variable_dict[x])

and I use the txt string to populate the list box.

At first glance, it seems to work, as the names are on the left, and the tuples
are in a column...

But if you scroll the listbox, the inherent error makes it appear as if the
tuple column is a snake doing the twist.

I tried using a tab but got a backslash - t in the text, and simply counting
spaces is worse than useless.

Is there a way to format this so it will line up with  *any*  font ?

I would prefer not to give up and use a fixed width font - it looks so
teletypish...

A blank char of one pixel width would sort this nicely - but as the hilbilly
said when he first saw a rhinoceros: " There aint no such animal! "  -  or is
there?

- Hendrik

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter Listbox string formatting question - how to kill a dancingsnake ?

2006-10-31 Thread Hendrik van Rooyen

"Fredrik Lundh" <[EMAIL PROTECTED]> wrote:


> instead of trying to force the listbox to behave like a multicolumn
> widget, maybe you could switch to another widget?  some alternatives include
>
>  a Text widget (you have to roll your own selection logic)

I _really_ don't feel strong enough for this, or for sticking them loose on a
canvas...

>  bwidgets multicolumn ListBox:
>  http://tkinter.unpythonic.net/bwidget/
>  tktable:
>  http://tktable.sourceforge.net/
>  something based on the wck (that's what I'd would use myself):
>  http://effbot.org/zone/wck-4.htm
>  and perhaps there's something in Pmw:
>  http://pmw.sourceforge.net
> 

Thanks I will check these out...

- Hendrik

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter Listbox string formatting question - how to kill a dancingsnake ?

2006-11-02 Thread Hendrik van Rooyen

"Fredrik Lundh" <[EMAIL PROTECTED]> wrote:





In the meantime, I have produced this evil hack, that takes advantage of the
difference in pixel widths between the space, and either the fullstop or the
single quote...

It will only work if you have quite a lot of space to waste between columns, and
I have only tested it for two sizes of Lucida and Helvetica - and for a fixed
font like courier it seems to do no harm other than the cpu time it wastes...

If the difference in width is one pixel, it lines up the next thing to be added
to the string exactly, else it almost gets it right...

I find the few (up to one less than there are pixels in a space) characters it
adds into the line less visually disturbing than the dancing snake column caused
by the full space width variation.

anyway for what its worth, here it is:

# this does some text padding to try to line variable font stuff up

def pad_text(txt,pixlen,fontp):
"""This does padding up to a pixel value exploiting differences
between space, fullstop or single quote widths.
txt is a text string
pixlen is an int - the number of pixels to "tab" to
fontp is the font parameter
"""

a = fontp.measure(txt)
diff = pixlen - a
if diff < 0:
return "string too long too fit in pixels"
spsize = fontp.measure(' ')
fssize = fontp.measure('.')
sqsize = fontp.measure("'")
repchr = ' '
rpsize = spsize
numr = 0
rpdiff = 0
if spsize != fssize:
repchr = '.'
rpsize = fssize
rpdiff = abs(fssize - spsize)
elif spsize != sqsize:
repchr = "'"
rpsize = sqsize
rpdiff = abs(spsize - sqsize)
numspace, rem = divmod(diff,spsize)
if rem == 0:
numr = 0
else:
if spsize < rpsize:
numspace -= rem/rpdiff
numr = rem/rpdiff
elif spsize > rpsize:
numr = (spsize - rem)/rpdiff
numspace = numspace - numr + 1
numspace -= 2
txt = txt + '  '
while numr > 0:
txt = txt + repchr
numr -= 1
while numspace > 0:
txt = txt + ' '
numspace -= 1
return txt

Feel free to play the critic...

- Hendrik


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MySQLDB - parameterised SQL - "TypeError: not all arguments converted during string formatting"

2006-02-19 Thread shearichard
Hi Dennis - Thanks for your help with this 

Dennis Lee Bieber wrote:
> On 19 Feb 2006 16:26:15 -0800, [EMAIL PROTECTED] declaimed the
> following in comp.lang.python:
>
> > Hi - I have written some python to insert a row into a table using
> > MySQLDB. I have never before written SQL/Python using embedded
> > parameters in the SQL and I'm having some difficulties. Could someone
> > point me in the right direction please ?
> > sqlQuery = "INSERT INTO EVA_COMPANY
> > (COM_ADDRESS,COM_AUTOID,COM_COMPANY_ADDRESS,COM_STRUCT_OWNER_CODE)
> > VALUES (?,?,?,?) "
>
>   One: I believe MySQLdb uses %s placeholders, not ?
>
> >>> import MySQLdb
> >>> MySQLdb.paramstyle
> 'format'
>
> From the DB-API PEP
>
>  paramstyle
>
> String constant stating the type of parameter marker
> formatting expected by the interface. Possible values are
> [2]:
>
> 'qmark' Question mark style,
> e.g. '...WHERE name=?'
> 'numeric'   Numeric, positional style,
> e.g. '...WHERE name=:1'
> 'named' Named style,
> e.g. '...WHERE name=:name'
> 'format'ANSI C printf format codes,
> e.g. '...WHERE name=%s'
> 'pyformat'  Python extended format codes,
> e.g. '...WHERE name=%(name)s'
>
>

Great stuff. I had seen some example code which used question marks and
rather too slavishly used it as a model. As you say MySQLDb does indeed
use 'format' and so %s are the way to go ...

>
> > print sqlQuery
> > sql = cursor.execute(sqlQuery,("test","NULL","Tester1017",5))
>
>   Two: I think it is smart enough to translate a Python None to a
> MySQL NULL -- which is different from a four-character string containing
> NULL (or even a zero-character string "").

... just to confirm that yes using a Python None works fine if you wish
to put a Null into a column ...
>
> >
> > CREATE TABLE `eva_company` (
> >   `COM_AUTOID` int(9) unsigned NOT NULL auto_increment,
>
>   As an auto-increment field, the recommendation would be to not even
> mention the field in the INSERT SQL -- that also takes care of the
> problem of specifying NULL to a non-null field!
>

... yes it didn't start off that way but I was busy trying everthing I
could think of to try to make it happier.

thanks for your help it's all working now.

regards

richard.




> --
>  > == <
>  >   [EMAIL PROTECTED]  | Wulfraed  Dennis Lee Bieber  KD6MOG <
>  >  [EMAIL PROTECTED] |   Bestiaria Support Staff   <
>  > == <
>  >   Home Page: <
>  >Overflow Page: <

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter Listbox string formatting question - how to kill a dancing snake ?

2006-10-31 Thread Fredrik Lundh
Hendrik van Rooyen wrote:

> Is there a way to format this so it will line up with  *any*  font ?
> 
> I would prefer not to give up and use a fixed width font - it looks so
> teletypish...

sounds like contradicting requirements to me.

instead of trying to force the listbox to behave like a multicolumn 
widget, maybe you could switch to another widget?  some alternatives include

 a Text widget (you have to roll your own selection logic)
 bwidgets multicolumn ListBox:
 http://tkinter.unpythonic.net/bwidget/
 tktable:
 http://tktable.sourceforge.net/
 something based on the wck (that's what I'd would use myself):
 http://effbot.org/zone/wck-4.htm
 and perhaps there's something in Pmw:
 http://pmw.sourceforge.net


-- 
http://mail.python.org/mailman/listinfo/python-list


Can string formatting be used to convert an integer to its binary form ?

2006-09-28 Thread [EMAIL PROTECTED]
Hi,

String formatting can be used to converting an integer to its octal or 
hexadecimal form:
 >>> a = 199
 >>> "%o" % a
'307'
 >>> "%x" % a
'c7'

But, can string formatting be used to convert an integer to its binary 
form ?


Thanks in advance.

xiaojf
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can string formatting be used to convert an integer to its binary form ?

2006-09-28 Thread flupke
[EMAIL PROTECTED] schreef:
> Hi,
> 
> String formatting can be used to converting an integer to its octal or
> hexadecimal form:
>>>> a = 199
>>>> "%o" % a
> '307'
>>>> "%x" % a
> 'c7'
> 
> But, can string formatting be used to convert an integer to its binary
> form ?
> 
> 
> Thanks in advance.
> 
> xiaojf

I don't actually know how to do it with string formatting but you can
create a simple function to do it.
Here's an example:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/219300

Regards,
Benedict
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can string formatting be used to convert an integer to its binary form ?

2006-09-28 Thread Mirco Wahab
Thus spoke [EMAIL PROTECTED] (on 2006-09-28 09:10):

> String formatting can be used to converting an integer to its octal or 
> hexadecimal form:
>  >>> a = 199
>  >>> "%o" % a
> '307'
>  >>> "%x" % a
> 'c7'
> 
> But, can string formatting be used to convert an integer to its binary 
> form ?

I didn't fell over this problem so far but
I *would* have expected to find something
like a 'pack' operator (as in Perl).

And voilá, there is (even basically identical to Perl):

  from struct import *

  a = 199
  a_bin_str = pack('L', a)



Regards

Mirco
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can string formatting be used to convert an integer to its binary form ?

2006-09-28 Thread Gabriel Genellina

At Thursday 28/9/2006 05:22, Mirco Wahab wrote:


> String formatting can be used to converting an integer to its octal or
> hexadecimal form:
>  >>> a = 199
>  >>> "%o" % a
> '307'
>  >>> "%x" % a
> 'c7'
>
> But, can string formatting be used to convert an integer to its binary
> form ?

  a = 199
  a_bin_str = pack('L', a)


Notice that the OP was looking for another thing, given the examples. 
Perhaps a better wording would have been "how to convert an integer 
to its base-2 string representation".



Gabriel Genellina
Softlab SRL 






__
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas


-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Can string formatting be used to convert an integer to its binary form ?

2006-09-28 Thread Mirco Wahab
Thus spoke Gabriel Genellina (on 2006-09-28 11:05):

> At Thursday 28/9/2006 05:22, Mirco Wahab wrote:
>> > But, can string formatting be used to convert an integer to its binary
>> > form ?
>>
>>   a = 199
>>   a_bin_str = pack('L', a)

> 
> Notice that the OP was looking for another thing, given the examples. 
> Perhaps a better wording would have been "how to convert an integer 
> to its base-2 string representation".

Yes, you are right. The OP looks for a
'binary (bit) representation ..."
I admit I didn't find out how to format
a value into a bit string in Python.

In Perl, this would be a no-brainer:

  $var = 199;
  $str = sprintf "%0*b", 32, $var;

and str would contain 11000111
on a intel machine.

But where is the %b in Python?

Regards & Thanks

Mirco
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can string formatting be used to convert an integer to its binary form ?

2006-09-28 Thread bearophileHUGS
Mirco Wahab:
> But where is the %b in Python?

Python doesn't have that. You can convert the number to a hex, and then
map the hex digitds to binary strings using a dictionary, like this:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440528

Bye,
bearophile

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can string formatting be used to convert an integer to its binary form ?

2006-09-28 Thread Frederic Rentsch
[EMAIL PROTECTED] wrote:
> Mirco Wahab:
>   
>> But where is the %b in Python?
>> 
>
> Python doesn't have that. You can convert the number to a hex, and then
> map the hex digitds to binary strings using a dictionary, like this:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440528
>
> Bye,
> bearophile
>
>   
Good idea, but shorter with -> 
http://cheeseshop.python.org/pypi/SE/2.2%20beta

 >>> import SE
 >>> Int_To_Binary = SE.SE (SE.SE ('0= 1=0001 2=0010 3=0011 4=0100 
5=0101 6=0110 7=0111 8=1000 9=1001 A=1010 a=1010 B=1011 b=1011 C=1100 
c=1100 D=1101 d=1101 E=1110 e=1110 F= f=')
 >>> Int_To_Binary ('%x' % 1234567890')
'0100100110010110001011010010'

 >>> Int_To_Binary.save ('se_definition_files/int_to_binary.se')

 >>> SE.SE ('se_definition_files/int_to_binary.se') ('%X' % 987654321)
'0011101011000110100010110001'


Frederic

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can string formatting be used to convert an integer to its binary form ?

2006-09-28 Thread Mirco Wahab
Thus spoke Frederic Rentsch (on 2006-09-28 20:43):
> [EMAIL PROTECTED] wrote:
>> Mirco Wahab:
>>   
>>> But where is the %b in Python?
>>
>> Python doesn't have that. ...
>> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440528
>   
> Good idea, but shorter with -> 
> http://cheeseshop.python.org/pypi/SE/2.2%20beta
> SE.SE ('se_definition_files/int_to_binary.se') ('%X' % 987654321)
> '0011101011000110100010110001'

I don't really understand here:

- why doesn't have Python such a simple and useful thing as to_binstr(...)
  even C++ has one built in,
#include 
#include 

int somefunc()
   {
int val = 199;
std::cout << std::bitset<32>( val );
...

- why would you favor such complicated solutions
  for this (as posted), when you can have this
  in one line, e.g.:

  def int2bin(num, width=32):
return ''.join(['%c'%(ord('0')+bool((1

Re: Can string formatting be used to convert an integer to its binary form ?

2006-09-28 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Mirco Wahab wrote:

> Thus spoke Frederic Rentsch (on 2006-09-28 20:43):
>> [EMAIL PROTECTED] wrote:
>>> Mirco Wahab:
>>>   
 But where is the %b in Python?
>>>
>>> Python doesn't have that. ...
>>> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440528
>>   
>> Good idea, but shorter with -> 
>> http://cheeseshop.python.org/pypi/SE/2.2%20beta
>> SE.SE ('se_definition_files/int_to_binary.se') ('%X' % 987654321)
>> '0011101011000110100010110001'
> 
> I don't really understand here:
> 
> - why doesn't have Python such a simple and useful thing as to_binstr(...)

Maybe simple, but useful?  And if you really need this it's simple to
implement or look up in the cook book.

> - why would you favor such complicated solutions
>   for this (as posted), when you can have this
>   in one line, e.g.:
> 
>   def int2bin(num, width=32):
> return ''.join(['%c'%(ord('0')+bool((1< range((width-1),-1,-1)])

Yeah, I wonder why not everybody sees the beauty in this cool and
straightforward one liner.  ;-)

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can string formatting be used to convert an integer to its binary form ?

2006-09-28 Thread Fredrik Lundh
Mirco Wahab wrote:

> - why doesn't have Python such a simple and useful thing as to_binstr(...)

useful?  really?  for what?



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can string formatting be used to convert an integer to its binary form ?

2006-09-28 Thread Mirco Wahab
Thus spoke Marc 'BlackJack' Rintsch (on 2006-09-28 23:38):

>>   def int2bin(num, width=32):
>> return ''.join(['%c'%(ord('0')+bool((1<> range((width-1),-1,-1)])
> 
> Yeah, I wonder why not everybody sees the beauty in this cool and
> straightforward one liner.  ;-)

Right. I see this is BS, maybe lots of these lines exist already,
one could come up with (sorted by obfuscation, descending):

def int2bin(num, width=32):
#  return ''.join( [chr(ord('0')+bool(1<>k & 1),range(width-1, -1, -1)) )
#  return ''.join( [str(num>>k & 1)for k in range(width-1, -1, -1)] )

But after some thinking, I thought about discussing this one:

def i2b(num, width):
  return str(1 & num>>(width-1)) + i2b(num, width-1) if width else ''

which is the shortest ;-)

(Sorry but I'm more or less a newbie, maybe this is BS too ...)

Regards

Mirco
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can string formatting be used to convert an integer to its binary form ?

2006-09-28 Thread Mirco Wahab
Thus spoke Fredrik Lundh (on 2006-09-28 23:35):

> Mirco Wahab wrote:
> 
>> - why doesn't have Python such a simple and useful thing as to_binstr(...)
> 
> useful?  really?  for what?

I don't really know, but according to google,
people often ask exactly for that and there
is no reason at all why one shouldn't expect
to get a /bit string/ from "%b" %.

So if people think it's badly needed, how
couldn't it be *not* useful then? ;-)

It feels to me (as it does sometimes
when diving into Python, to be honest)
simply as a shortcoming, - and the ter-
nary operator included in 2.5 was
imho a huge step forward, next will
be mutable strings and arrays will be
'called arrays' somewhere ... ;-)

(maybe somebody reverses the -v/-V switch too, hey)

Regards

Mirco
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can string formatting be used to convert an integer to its binary form ?

2006-09-28 Thread bearophileHUGS
Frederic Rentsch:
> Good idea, but shorter with ->
>  >>> SE.SE ('se_definition_files/int_to_binary.se') ('%X' % 987654321)
> '0011101011000110100010110001'

Note that your version keeps the leading zeros.
Have you tested the relative speeds too?
(I'll probably have to learn to use SE.)

Bye,
bearophile

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can string formatting be used to convert an integer to its binary form ?

2006-09-28 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, [EMAIL PROTECTED] wrote:

> Mirco Wahab:
>> But where is the %b in Python?
> 
> Python doesn't have that. You can convert the number to a hex, and then
> map the hex digitds to binary strings using a dictionary, like this:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440528

How about this: (where n is the integer you want to convert):

"".join([["0", "1"][(1 << i & n) != 0] for i in 
range(int(math.ceil(math.log(n, 2))) - 1, -1, -1)])

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can string formatting be used to convert an integer to its binary form ?

2006-09-28 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, I wrote:

> "".join([["0", "1"][(1 << i & n) != 0] for i in 
> range(int(math.ceil(math.log(n, 2))) - 1, -1, -1)])

Uh, make that

"".join([["0", "1"][(1 << i & n) != 0] for i in 
range(int(math.floor(math.log(n, 2))), -1, -1)])

Need to check those corner cases. :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can string formatting be used to convert an integer to its binary form ?

2006-09-28 Thread Gabriel Genellina

At Thursday 28/9/2006 22:07, Lawrence D'Oliveiro wrote:


How about this: (where n is the integer you want to convert):

"".join([["0", "1"][(1 << i & n) != 0] for i in 
range(int(math.ceil(math.log(n, 2))) - 1, -1, -1)])


Uhm... so to generate a binary string you have to import the math 
module, convert the integer to float, compute a non-standard 
logarithm, and then...

What if n<=0?
Too much, don't you think? :)


Gabriel Genellina
Softlab SRL 






__
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas


-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Can string formatting be used to convert an integer to its binary form ?

2006-09-28 Thread George Sakkis
Gabriel Genellina wrote:

> At Thursday 28/9/2006 22:07, Lawrence D'Oliveiro wrote:
>
> >How about this: (where n is the integer you want to convert):
> >
> > "".join([["0", "1"][(1 << i & n) != 0] for i in
> > range(int(math.ceil(math.log(n, 2))) - 1, -1, -1)])
>
> Uhm... so to generate a binary string you have to import the math
> module, convert the integer to float, compute a non-standard
> logarithm, and then...
> What if n<=0?
> Too much, don't you think? :)

Having recently discovered the joy of obfuscated python thanks to the
Code Golf challenges, here's the shortest non-recursive function I came
up with (all integers, signed):

f=lambda n:'-'[:n<0]+''.join(str(m&1)for m in iter(
  lambda x=[abs(n)]:(x[0],x.__setitem__(0,x[0]>>1))[0],0))[::-1]or'0'

Any takers ? ;-)

George

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can string formatting be used to convert an integer to its binary form ?

2006-09-28 Thread MonkeeSage
So far as unobfuscated versions go, how about the simple:

def to_bin(x):
  out = []
  while x > 0:
out.insert(0, str(x % 2))
x = x / 2
  return ''.join(out)

Regards,
Jordan

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can string formatting be used to convert an integer to its binary form ?

2006-09-28 Thread Steve Holden
MonkeeSage wrote:
> So far as unobfuscated versions go, how about the simple:
> 
> def to_bin(x):
>   out = []
>   while x > 0:
> out.insert(0, str(x % 2))
> x = x / 2
>   return ''.join(out)
> 
> Regards,
> Jordan
> 
  >>> to_bin(0)
''

6/10: try harder :)

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can string formatting be used to convert an integer to its binary form ?

2006-09-28 Thread Paul Rubin
"MonkeeSage" <[EMAIL PROTECTED]> writes:
> def to_bin(x):
>   out = []
>   while x > 0:
> out.insert(0, str(x % 2))
> x = x / 2
>   return ''.join(out)

That returns the empty string for x=0.  I'm not sure if that's a bug
or a feature.

It also returns the empty string for x < 0, probably a bug.

It will break in Python 3, where 1 / 2 == 0.5.

Here's yet another version:

def to_bin(n):
if n < 0: return '-' + to_bin(-n)
if n==0: return '0'
return ''.join(
("", "0001", "0010", "0011",
"0100", "0101", "0110", "0111",
"1000", "1001", "1010", "1011",
"1100", "1101", "1110", "",)[int(d,16)] \
for d in '%x'%n).lstrip('0')
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >