首页 > 解决方案 > f-strings 是 python(3.6 及更高版本)的独特功能吗?

问题描述

使用 f 字符串,您可以使用一些变量值直接在字符串中填充“占位符”。反对,让我们说使用 str.format() 方法,经常看到。

例子:

In [1]: x=3
In [2]: y=4
In [3]: print(f'The product of {x} and {y} is {x*y}.')
The product of 3 and 4 is 12.

这个 f-strings 的概念是否只在 python 中找到?或者是否有任何其他语言支持这一点,可能使用不同的名称?

标签: pythonpython-3.xlanguage-conceptsf-string

解决方案


简短的回答:不 - 不是 python 独有的。在 python 中,它是由Literal String Interpolation - PEP 498在 3.6 中引入的

在 C# 中有$ - 字符串插值作为某些函数的简写,您可以将String.Format用于:

string val = "similar";
string s = $"This is {val}"     // s == "This is similar"

// vs. 

var s2 = string.Format ("This is {0}", val); // {0} = 0th param that follows

推荐阅读