print('%s is (%d+10) years old' % ('Joe', 42))
Output: Joe is (42+10) years old
Expected output: Joe is 52 years old
You can do this with f-strings in Python 3.6+.
name = "Joe"
age = 42
print(f'{name} is {age + 10} years old')
String formatting insert values into a string. To operate on a value you should compute the value first and then insert/format it into the string.
print('%s is %d years old' % ('Joe', 42 + 10)
# or if you really want to something like that (python 3.6+)
name = 'joe'
age = 42
f'{name} is {age +10} years old'
You cannot do arithmetic operations inside a string.
print('%s is (%d) years old' % ('Joe', 42+10))
F-strings
(PEP 498 : Python V 3.6) can handle your case better since f-string
expression are evaluated at run time. For e.g:
name = 'Joe'
a, b = 42, 10
print(f'{name} is {a + b} years old')
You are adding the values inside the string which is wrong.
print('%s is %d years old' % ('Joe', 42+10))
Three ways
print('%s is %d years old' % ('Joe', 42+10))
print('{0} is {1} years old'.format('Joe', 42+10))
name='Joe'
print(f'{name} is {42+10} years old')
Just some other ways to print
print(name,'is',(42+10),'years old')
print(eval("name + ' is ' + str(42+10) + ' years old'"))
print('%s is (%d+10) years old' % ('Joe', 42)
name='joe'
age=42+10
print(f'{name} is {age} years old')
Here I am using Template string to perform this action using another approach.It’s a simpler and less powerful mechanism.
The best time to use template strings is when you’re handling formatted strings generated by users of your program. Due to their reduced complexity, template strings are a safer choice.
Here is the example of template string:
>>>from string import Template
>>>name = 'Joe'
>>>age=42
>>>t = Template('$name is $age years old')
>>>t.substitute(name = name, age=age+10)
output
'Joe is 52 years old'