Sage % symbol
I am a beginner to Sage. During learning Sage I found a code snippet here
for i in range(5):
print('%6s %6s %6s' % (i, i^2, i^3))
Can anybody explain why %()
is used here ?
This is a string formatting symbol. Suppose you have several items a,b,c
in Sage (or Python more generally) you wish to print, but you want them to be printed in the midst of a longer statement.
a, b, c, = 1, 2, 3
Then to do so, rather than something error-prone like this
print('My first number is ' + str(a) + ' then I have ' + str(b) + ' and also ' + str(c))
or several variants thereon, it is easier and more adaptable to do
print('My first number is %s then I have %s and also %s' %(a, b, c))
This says that you replace each %s
with the next item in the tuple (a,b,c)
. If now you realized they were in the wrong order, it's very easy to fix that:
print('My first number is %s then I have %s and also %s' %(c, b, a))
Note that %s
is for string formatting; there are other ways to format numbers as well. The one in your example is padding with extra spaces.
print('My first number is %6s then I have %6s and also %6s' %(a, b, c))
See this link for an active example.
The Python documentation for this is quite technical; see this site for some good examples.
Thank you for the answer. I found some documentation about %
here. It basically says that %
is a operator. Similar to operator overloading in C++, it is a modulus operator in Sage too. Can you update your answer to reflect the similar view as of the documentation. It is more clearer.
I'm not sure exactly what you want me to clarify, but your comment will hopefully achieve that purpose to future readers of this post. Yes, %
is also an operator, but I was only referring to the string formatting purpose.
Note that the %
is kind of being deprecated in favor of the format
method, your snippet will be replaced as follows:
sage: for i in range(5):
....: print('{:>6} {:>6} {:>6}'.format(i, i^2, i^3))
0 0 0
1 1 1
2 4 8
3 9 27
4 16 64
True, though apparently not really deprecated, as it turns out. For short things the "old syntax" probably still suffices, though I find the new syntax nicer for more flexibility.
Please start posting anonymously - your entry will be published after you log in or create a new account.
Asked: 8 years ago
Seen: 1,240 times
Last updated: Apr 10 '17