如何在Python中对整数占位符执行操作?

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

输出: Joe 现在 (42+10) 岁了。

期望输出: Joe 现在 52 岁了。

8个回答

13

你可以使用Python 3.6+中的f-strings实现这一点。

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

5

字符串格式化是向字符串中插入值。要对一个值进行操作,你应该先计算这个值,然后再将其插入/格式化到字符串中。

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

F-stringsPEP 498 : Python V 3.6)可以更好地处理您的情况,因为f-string表达式在运行时进行评估。例如:

name = 'Joe'
a, b = 42, 10
print(f'{name} is {a + b} years old')

3

你不能在字符串内进行算术运算。

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

2
您正在对字符串中的值进行相加,这是错误的。
print('%s is %d years old' % ('Joe', 42+10))

1
三种方式
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')

只是另外一些打印的方法

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

在这里,我使用模板字符串来使用另一种方法执行此操作。它是一种更简单且不那么强大的机制

使用模板字符串的最佳时机是处理程序的用户生成的格式化字符串时。由于其复杂性降低,模板字符串是更安全的选择。

以下是模板字符串的示例:

>>>from string import Template
>>>name = 'Joe'
>>>age=42
>>>t = Template('$name is $age years old')
>>>t.substitute(name = name, age=age+10)

输出

'乔是52岁'


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接