开发者

Evaluation inside string

Is there something like Rubys "Hello #{userNameFu开发者_JS百科nction()}" in python?


In Python, you would use string interpolation

"Hello %s" % user_name_function()

or string formating

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

The latter is available in Python 2.6 or above.

Also note that by convention you don't use CamelCase for function names in Python (CamelCase is for class names only -- see PEP 8).


Python's string interpolation is the closest to what you want.

The most common form is:

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

This makes use of a tuple to supply the data in the order they are needed in the string.

But, you can also use a dict and use meaningful names for the data that you need inside the string:

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


In Python 2.4+ you can use the Templateclass in the stringmodule to do things like this:

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'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜