Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #41996
| From | Frank Millman <frank@chagford.com> |
|---|---|
| Subject | Re: True/False formats as 1/0 in a fixed width string |
| Date | 2013-03-27 11:22 +0200 |
| References | <kiub99$q9u$1@ger.gmane.org> <5152B407.50801@davea.name> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.3801.1364376154.2939.python-list@python.org> (permalink) |
On 27/03/2013 10:55, Dave Angel wrote:
> On 03/27/2013 04:40 AM, Frank Millman wrote:
>> Hi all
>>
>> This is a bit of trivia, really, as I don't need a solution.
>>
>> But someone might need it one day, so it is worth mentioning.
>>
>> >>> '{}'.format(True)
>> 'True'
>> >>> '{:<10}'.format(True)
>> '1 '
>>
>> One might want to format True/False in a fixed width string, but it
>> returns 1/0 instead. Is there any way to make this work?
>>
>> Frank Millman
>>
>
> Easiest way is to surround the boolean variable with repr()
>
> flag = True
> '{:<10}'.format(repr(flag))
>
> An alternative is to just use something like:
>
> ["False ","True "][flag]
>
> making sure the two strings are of the same length.
>
> (You didn't specify version, but I tested these with CPython 2.7.3)
>
Thanks, Dave. I am using CPython 3.3.0, which behaves the same for this
purpose.
Your solutions work, but in my case I am reading in data from a
database, so I want to create a format string, and then just call
print(format_string.format(*row))
so I can't easily modify the contents of a single column.
Peter's solution works perfectly for this scenario -
>>> '{!s:<10}'.format(True)
'True '
I had to look up what '!s' means. From the manual -
"Three conversion flags are currently supported: '!s' which calls str()
on the value, '!r' which calls repr() and '!a' which calls ascii()."
Another obscure but useful tip to store away somewhere.
Frank
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: True/False formats as 1/0 in a fixed width string Frank Millman <frank@chagford.com> - 2013-03-27 11:22 +0200
csiph-web