Reputation: 103
I'm trying to print stuff on python 3.4.3 on the following way:
a=1
b=2
print("text text %2d text text %2d", %(a,b))
but when I try to run this simple code it appears a mark exactly over the last "%" sign "invalid syntax":
File "<stdin>", line 1
print("text text %2d text text %2d", %(a,b))
^
SyntaxError: invalid syntax
Upvotes: 0
Views: 1545
Reputation: 107347
You dont need comma after Your string :
print("text text %2d text text %2d" %(a,b))
The % operator can also be used for string formatting. It interprets the left argument much like a sprintf()-style format string to be applied to the right argument, and returns the string resulting from this formatting operation
Also python documentation says :
because this old style of formatting will eventually be removed from the language,
str.format()
should generally be used.
So you can use str.format
:
print("text text {:2d} text text {:2d}".format(a,b))
Upvotes: 2
Reputation: 1124378
You need to remove the comma:
print("text text %2d text text %2d", %(a,b))
# ^
The %
is an binary operator, it works on two inputs. Here those inputs are the string and the (a, b)
tuple:
print("text text %2d text text %2d" % (a,b))
Upvotes: 1