gpt4 book ai didi

python - 将变量放入字符串中(引用)

转载 作者:太空狗 更新时间:2023-10-29 22:15:20 25 4
gpt4 key购买 nike

求助,我无法让它工作,我试图将变量 age 放入字符串中,但它无法正确加载变量。

这是我的代码:

import random
import sys
import os


age = 17
print(age)
quote = "You are" age "years old!"

给出这个错误:

File "C:/Users/----/PycharmProjects/hellophyton/hellophyton.py", line 9
quote = "You are" age "years old!"
^
SyntaxError: invalid syntax

Process finished with exit code 1

最佳答案

您应该在此处使用字符串格式化程序或连接。对于连接,您必须将 int 转换为 string。您不能将整数和字符串连接在一起。

如果您尝试这将引发以下错误:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

格式:

quote = "You are %d years old" % age
quote = "You are {} years old".format(age)

串联(单向)

quote = "You are " + str(age) + " years old" 

编辑:正如 J.F. Sebastian 在评论中指出的那样,我们还可以执行以下操作

在 Python 3.6 中:

f"You are {age} years old"

早期版本的 Python:

"You are {age} years old".format(**vars())

关于python - 将变量放入字符串中(引用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37015485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com