Что такое эквивалент Python встраивания выражения в строку? (т.е. "# {expr}" в Ruby)
В 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
Ответы
Ответ 1
Если вам нужно больше, чем просто форматирование строки, предоставленное str.format()
и %
, тогда templet
модуль можно использовать для вставки выражений 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))
Выход
This is a sample string
that references a function whose value is: 100
Incrementing the value: 101
Шаблоны Python с функцией @string.
Ответ 2
Использование метода формата:
>>> '{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'
Ответ 3
Используйте format
метод:
>>> get_val = 999
>>> 'This is the string containing the value of get_val which is {get_val}'.format(**locals())
'This is the string containing the value of get_val which is 999'
**locals
передает словарь локальных переменных в качестве аргументов ключевого слова.
{get_val}
в строке обозначает место, где значение переменной get_val
должно быть напечатано. Существуют и другие варианты форматирования. См. docs метода format
.
Это сделает вещи почти такими же, как в Ruby. (с той лишь разницей, что в Ruby вам нужно положить #
для фигурных скобок #{get_val}
).
Если вам нужно вывести incremented 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'
Ответ 4
Как программист C и Ruby, мне нравится классический подход printf
:
>>> 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.
Ответ 5
Polyglot.org отвечает на многие вопросы, подобные этим для PHP, Perl, Python и Ruby.