Skip to content Skip to sidebar Skip to footer

Evaluation Inside String

Is there something like Rubys 'Hello #{userNameFunction()}' in python?

Solution 1:

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).

Solution 2:

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'

Solution 3:

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

from string import Template

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

Post a Comment for "Evaluation Inside String"