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


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


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: 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


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