Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Python equivalent of embedding an expression in a string? (ie. "#{expr}" in Ruby)

In Python, I'd like to create a string block with embedded expressions.
In Ruby, the code looks like this:

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
like image 907
hopia Avatar asked Dec 04 '22 17:12

hopia


2 Answers

Update: since Python 3.6, there are formatted string literals (f-strings) which enable a literal string interpolation: f"..{get_val()+1}..."


If you need more than just a simple string formatting provided by str.format() and % then templet module could be used to insert Python expressions:

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

Output

This is a sample string
that references a function whose value is: 100
Incrementing the value: 101

Python Templating with @stringfunction.

like image 184
jfs Avatar answered Dec 29 '22 00:12

jfs


Using the format method:

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

Format by name:

>>> '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'
like image 43
Laurens Avatar answered Dec 29 '22 01:12

Laurens