# 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 ?

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 ?

add a comment

1

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.

0

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
```

Asked: **
2017-04-09 23:17:36 -0600
**

Seen: **58 times**

Last updated: **Apr 10 '17**

Complex forms and differentials

How to get more uniform output from full_simplify

Has anyone looked at nltk in Sage?

Multiplicities of solutions not showing up correctly

where is basic tutorial for sage

block_matrix confusion (matrix constructor rewrite in new versions of Sage)

Using the solution of a linear system, and splitting a matrix

Copyright Sage, 2010. Some rights reserved under creative commons license. Content on this site is licensed under a Creative Commons Attribution Share Alike 3.0 license.