有没有办法在不使用 print 函数的情况下将变量插值到 python 字符串中?

Is there a way to interpolate variables into a python string WITHOUT using the print function?

提问人:skeetastax 提问时间:10/31/2023 更新时间:10/31/2023 访问量:47

问:

我见过的每个 Python 字符串变量插值示例都使用该函数。print

例如:

num = 6

# str.format method
print("number is {}".format(num))

# % placeholders
print("number is %s"%(num))

# named .format method
print("number is {num}".format(num=num))

您可以在不使用 的情况下将变量插值到字符串中吗?print

python 字符串 变量 format string-interpolation

评论

3赞 Ch3steR 10/31/2023
"number is {num}".format(num=num)给你一个字符串。 只是打印它。 会很好用。prints = "number is {num}".format(num=num); print(s)
2赞 Ch3steR 10/31/2023
我见过的每个 Python 字符串变量插值示例都使用 print 函数。这是为了显示插值的输出。
1赞 tdelaney 10/31/2023
你可以在很多地方做到这一点。赋值给变量,例如:。在不同的函数中使用 )for c in “number is {num}”.format(num=num): .format' 方法。foo = "number is {num}".format(num=num)foo("number is {num}".format(num=num). You can even iterate them . In this case "number is {num}" is a string object with a
1赞 Mayur 10/31/2023
str=f"number is {num}"
0赞 deceze 10/31/2023
@Mayur请不要重新声明 str...

答:

0赞 skeetastax 10/31/2023 #1

还行。。。所以,这很容易。

旧方法:

num = 6
mystr = 'number is %s' % num
print(mystr) # number is 6

较新的方法:.format

num = 6
mystr = "number is {}".format(num)
print(mystr) # number is 6

使用命名变量的方法(在无法依赖序列时很有用):.format

num = 6
mystr = "number is {num}".format(num=num)
print(mystr) # number is 6

较短的方法:(谢谢@mayur)f-string

num = 6
mystr = f"number is {num}"
print(mystr) # number is 6
1赞 tdelaney 10/31/2023 #2

在每种情况下,您都有一个对象。它的方法将格式化的字符串作为新对象返回。python 在看到运算符时调用它的方法也返回一个格式化的字符串。str.format__mod__%

函数和方法返回匿名对象。调用它们的上下文决定了接下来会发生什么。

"number is {num}".format(num=num)

扔掉结果。

some_variable = "number is {num}".format(num=num)

分配结果。

some_function("number is {num}".format(num=num))

调用以结果作为参数的函数。 不是特例 - python 不会对 .printprint

有趣的是,f-strings like 被编译成一系列动态构建字符串的指令。f"number is {num}"

评论

0赞 skeetastax 10/31/2023
谢谢,这是有用的信息。