[Python-ideas] Outside the box string formatting idea
Ron Adam
ron3200 at gmail.com
Tue Aug 11 22:09:42 CEST 2015
On 08/10/2015 01:40 AM, Vito De Tullio wrote:
> what about a slightly different "f"?
>
> def f(*args):
> f_args = []
> for arg in args:
> if isinstance(arg, tuple):
> f_args.append(format(*arg))
> else:
> f_args.append(format(arg))
> return ''.join(f_args)
>
> import datetime
> name = 'Fred'; age = 50; anniversary = datetime.date(1991, 10, 12)
> print(f('My name is ', name, ', my age next year is ', age+1,
> ', my anniversary is ', (anniversary, ':%A, %B %d, %Y'), '.'))
>
>
> My name is Fred, my age next year is 51, my anniversary is :Saturday,
> October 12, 1991.
What makes this difficult is it's a trinary operation combining three kinds
of data. If it was a pure binary operation it would be simple.
So the possible relationships are...
1. (string with format codes) + values # % and .format()
2. string + (formated values)
3. (string with values) + format codes
4. (string with both format codes and values) #f-strings
5. string + format codes + values # trinary operation?
#2 is interesting. It can already be done by calling format(value, fmt).
But maybe it can be improved on.
If it had a dedicated operator, it might be nice enough to fill most needs.
One of the main complaints with .format(...) is the length of the name,
and it adds another level of parentheses.
It can be split into separate fill and format operators and let precedence
handle things to avoid conflicts with passing tuples.
A quick hack...
class S:
def __init__(self, value):
self.value = value
def __lshift__(self, other):
"""Fill left most {}."""
return S(str(self.value).replace('{}', str(other), 1))
def __rfloordiv__(self, obj):
"""Format object with fmt string."""
return S(format(obj, self.value))
def __str__(self):
return str(self.value)
import datetime
name = 'Fred'
age = 50
anniversary = datetime.date(1991, 10, 12)
print(S('My name is {}, my age next year is {}, my anniversary is {}.')
<< name
<< (age+1)
<< anniversary // S('%A, %B %d, %Y'))
My name is Fred, my age next year is 51, my anniversary is Saturday,
October 12, 1991.
If those methods were added to strings, then it could look like this...
print('My name is {}, my age next year is {}, my anniversary is {}.'
<< name
<< (age+1)
<< anniversary // '%A, %B %d, %Y')
Other operators might be better, but those aren't that commonly used, and I
think they show the intents well.
Cheers,
Ron
More information about the Python-ideas
mailing list