Note that there are some explanatory texts on larger screens.

plurals
  1. POString formatting with “{0:d}” doesn't convert to integer
    primarykey
    data
    text
    <p>This is about the same issue as in <a href="https://stackoverflow.com/questions/5627605/string-formatting-with-0d-format-gives-unknown-format-code-d-for-object-o">this question about floats</a>.</p> <p>When you've got a value that could get converted to an integer, the old <code>%d</code> would convert it, but format doesn't.</p> <pre><code>class MyIntegerTenClass: def __int__(self): return 10 def __str__(self): return 'ten' ten = MyIntegerTenClass() print '%d, %02X, %s' % (ten, ten, ten) # ok print '{0}'.format(ten) # ok print '{0:d}, {0:02X}'.format(ten) # ValueError: Unknown format code 'd' for object of type 'str' </code></pre> <p>Is there a way to modify the behaviour of format, without touching the class of the value to be formatted (without adding a <code>__format__</code> method to that class)?</p> <p>Edit: My goal is to get the formatting dependent on the format string, but not on the value. So if the format string says "d" or "x", convert the value to int and then to decimal or hexadecimal representation. If the format string says "s", convert it to string directly. As the old <code>%</code> did.</p> <p>Actually, I could even add a <code>__format__</code> method to the class of the value. But how do I check, in that method, if the given format specification is an integer format specification? Without reimplementing the format specification parser of the builtin format.</p> <p>Edit: Here's a solution with <code>__format__</code> and exceptions. Any better ideas?</p> <pre><code>class MyIntegerTenClass: def __int__(self): return 10 def __str__(self): return 'ten' def __format__(self, spec): fmt = '{0:%s}'%spec try: return fmt.format(str(self)) except: return fmt.format(int(self)) ten = MyIntegerTenClass() print '%d, %02X, %s' % (ten, ten, ten) # ok, prints "10, 0A, ten" print '{0:d}, {0:02X}, {0}'.format(ten) # ok, prints "10, 0A, ten" </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload