I do this in Python 2:
"(%d goals, $%d)" % (self.goals, self.penalties)
What is the Python 3 version of this?
I tried searching for examples online but I kept getting Python 2 versions.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Here are the docs about the “new” format syntax. An example would be:
If both
goalsandpenaltiesare integers (i.e. their default format is ok), it could be shortened to:And since the parameters are fields of
self, there’s also a way of doing it using a single argument twice (as @Burhan Khalid noted in the comments):Explaining:
{}means just the next positional argument, with default format;{0}means the argument with index0, with default format;{:d}is the next positional argument, with decimal integer format;{0:d}is the argument with index0, with decimal integer format.There are many others things you can do when selecting an argument (using named arguments instead of positional ones, accessing fields, etc) and many format options as well (padding the number, using thousands separators, showing sign or not, etc). Some other examples:
Note: As others pointed out, the new format does not supersede the former, both are available both in Python 3 and the newer versions of Python 2 as well. Some may say it’s a matter of preference, but IMHO the newer is much more expressive than the older, and should be used whenever writing new code (unless it’s targeting older environments, of course).