string interpolation for python
Yingjie Lan
lanyjie at yahoo.com
Sat Mar 31 02:22:26 EDT 2012
Hi all,
I'd really like to share this idea of string interpolation for formatting.
Let's start with some code:
>>> name = "Shrek"
>>> print( "Hi, $name$!")
Hi, Shrek!
>>> balls = 30
>>> print( "We have $balls$ balls.")
We have 30 balls
>>> persons = 5
>>> print ("And $persons$ persons.")
And 5 persons.
>>> print(" Each may get exactly $balls//persons$ balls.")
Each may get exactly 6 balls.
>>> fraction = 0.12345
>>> print( "The fraction is $fraction : 0.2f$!")
The fraction is 0.12!
>>> print("It costs about $$3, I think.")
It costs about $3, I think.
I think the rule is quite self explanatory.
An expression is always enclosed between two '$'s,
with an optional ':' followed by additional formatting specification.
Double '$$' is like double '%%'.
Of course, '$' can be replaced by anything else.
For compatibility reasons, we might just use '%' as well.
============
Implementation: the compiler might need to do something,
say, to replace a string interpolation with an equivalent
expression.
Cheers,
Yingjie
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20120330/912f8a75/attachment-0001.html>
More information about the Python-list
mailing list