在字符串中嵌入表达式的Python等价物是什么?(即Ruby中的“expr”)
在Python中,我想用嵌入的表达式创建一个字符串块。在字符串中嵌入表达式的Python等价物是什么?(即Ruby中的“expr”),python,ruby,language-comparisons,string-interpolation,Python,Ruby,Language Comparisons,String Interpolation,在Python中,我想用嵌入的表达式创建一个字符串块。 在Ruby中,代码如下所示: def get_val 100 end def testcode s=<<EOS This is a sample string that references a variable whose value is: #{get_val} Incrementing the value: #{get_val + 1} EOS puts s end testcode def get\u
在Ruby中,代码如下所示:
def get_val
100
end
def testcode
s=<<EOS
This is a sample string that references a variable whose value is: #{get_val}
Incrementing the value: #{get_val + 1}
EOS
puts s
end
testcode
def get\u val
100
结束
def测试代码
s=使用方法:
**局部变量
将局部变量字典作为关键字参数传递。
字符串中的{get_val}
表示应打印变量的get_val
值的位置。还有其他格式选项。请参阅格式的
方法
这将使事情几乎像在Ruby中一样。(唯一的区别是,在Ruby中,必须在花括号{get\u val}
前面加上
)
如果您需要输出递增的get_val
,我认为除了以下方法之外,没有其他方法可以打印它:
>>> 'This is the string containing the value of get_val+1 which is {get_val_incremented}'.format(get_val_incremented = get_val + 1,**locals())
'This is the string containing the value of get_val+1 which is 1000'
使用格式化方法:
>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c') # 2.7+ only
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence
'c, b, a'
>>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated
'abracadabra'
按名称设置格式:
>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'
作为一名C和Ruby程序员,我喜欢经典的printf
-like方法:
>>> x = 3
>>> 'Sample: %d' % (x + 1)
'Sample: 4'
或者在多个参数的情况下:
>>> 'Object %(obj)s lives at 0x%(addr)08x' % dict(obj=repr(x), addr=id(x))
'Object 3 lives at 0x0122c788'
我已经能感觉到人们会为此痛打我。但是,我发现这一点特别好,因为它在Ruby中的工作方式与Ruby相同。更新:自Python 3.6以来,有几种方法支持文本字符串插值:
如果您需要的不仅仅是和提供的简单字符串格式,则可以使用模块插入Python表达式:
from templet import stringfunction
def get_val():
return 100
@stringfunction
def testcode(get_val):
"""
This is a sample string
that references a function whose value is: ${ get_val() }
Incrementing the value: ${ get_val() + 1 }
"""
print(testcode(get_val))
输出
.为PHP、Perl、Python和Ruby回答了许多类似的问题。现代Python中的等效程序使用f字符串。(f字符串语法是一种相对简单的语法。)
为什么在第二个示例中使用**locals
?另外,如果只有一个替换项,您可以将位置变量与{0}
一起使用。@NiklasB<代码>**locals
在第二个示例中,仅当字符串中显示一些其他变量时才需要(将来将它们添加到字符串中会更容易)。如果srting是固定的,并且没有预期的更改,那么第二个示例中的**locals()
是多余的。您只需要格式化一个值还是需要包含需要代码执行的表达式?Python 3有。format_map()
方法:坐标:{lation},{longitude}。format_map(坐标)
导入外部模块有点不方便,但这正是我想要的。
from templet import stringfunction
def get_val():
return 100
@stringfunction
def testcode(get_val):
"""
This is a sample string
that references a function whose value is: ${ get_val() }
Incrementing the value: ${ get_val() + 1 }
"""
print(testcode(get_val))
This is a sample string
that references a function whose value is: 100
Incrementing the value: 101
def get_val():
return 100
def testcode():
s = f"""
This is a sample string that references a variable whose value is: {get_val()}
Incrementing the value: {get_val() + 1}
"""
print(s)
testcode()