字符串中的求值

1 投票
3 回答
724 浏览
提问于 2025-04-16 13:33

在Python里,有没有类似于Ruby中"Hello #{userNameFunction()}"这样的写法呢?

3 个回答

1

在Python 2.4及以上版本中,你可以使用Template,这个类是在string模块里。它可以帮助你做一些类似这样的事情:

from string import Template

def user_name_function(): return "Dave"

s = Template('Hello $s')
print s.substitute(s=user_name_function())
# 'Hello Dave'

print s.substitute({'s': user_name_function()})
# 'Hello Dave'
2

Python中的字符串插值是最接近你想要的功能。

最常见的形式是:

>>> "Hello %s" % userNameFunction()
'Hello tm1brt'

这里使用了一个元组来按照需要的顺序提供数据。

不过,你也可以使用一个dict(字典),用有意义的名字来表示你在字符串中需要的数据:

>>> "Hello %(name)s" % {'name' : userNameFunction()}
'Hello tm1brt'
9

在Python中,你可以使用字符串插值

"Hello %s" % user_name_function()

或者字符串格式化

"Hello {0}".format(user_name_function())

后者在Python 2.6及以上版本中可以使用。

另外,按照惯例,在Python中函数名不使用驼峰命名法(驼峰命名法只用于类名——详细可以查看PEP 8)。

撰写回答