7
print('%s is (%d+10) years old' % ('Joe', 42))

Output: Joe is (42+10) years old

Expected output: Joe is 52 years old

8 Answers 8

13

You can do this with f-strings in Python 3.6+.

name = "Joe"
age = 42
print(f'{name} is {age + 10} years old')
5

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'
3

You cannot do arithmetic operations inside a string.

print('%s is (%d) years old' % ('Joe', 42+10))
0
3

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')
0
2

You are adding the values inside the string which is wrong.

print('%s is %d years old' % ('Joe', 42+10))
1

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'"))
0
print('%s is (%d+10) years old' % ('Joe', 42)
name='joe'
age=42+10
print(f'{name} is {age} years old')
0

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'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.