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.
This question is related to
python
python-3.x
string
Python 3.6 now supports shorthand literal string interpolation with PEP 498. For your use case, the new syntax is simply:
f"({self.goals} goals, ${self.penalties})"
This is similar to the previous .format
standard, but lets one easily do things like:
>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal('12.34567')
>>> f'result: {value:{width}.{precision}}'
'result: 12.35'
That line works as-is in Python 3.
>>> sys.version
'3.2 (r32:88445, Oct 20 2012, 14:09:29) \n[GCC 4.5.2]'
>>> "(%d goals, $%d)" % (self.goals, self.penalties)
'(1 goals, $2)'
I like this approach
my_hash = {}
my_hash["goals"] = 3 #to show number
my_hash["penalties"] = "5" #to show string
print("I scored %(goals)d goals and took %(penalties)s penalties" % my_hash)
Note the appended d and s to the brackets respectively.
output will be:
I scored 3 goals and took 5 penalties
Source: Stackoverflow.com