python variable expansion, format

background

Is it correct to call it variable expansion? How to embed a numerical value etc. in a character string variable.

ruby

name = "World"
month = 9
day = 9

print "Hellow #{name}!,today#{month}/#{day}is"

It's the one you want to see.

As a result of investigation

name = "World"
month = 9
day = 9

print u"Hellow {name}!,today{month}/{day}is".format(**locals())

It seems to write. .format (** locals ()) will quickly get annoying, and if you use it continuously Because it looks quite noisy

f = lambda x, l=locals(): x.format(**l)
print f(u"Hellow {name}!,today{month}/{day}is")

Will you do this?

Method

The idea is to deploy it using Jinja.


>>> from jinja2 import Template
>>> fj = lambda str, dict=locals(): Template(str).render(dict)
>>> name = "World"
>>> month = 9
>>> day = 9
>>> print fj(u"Hellow {{name}}!,today{{month}}/{{day}}is.")
Hellow World!,9 today/It is 9.
>>> print fj(u"tomorrow{{month}}/{{day+1}}is.")
9 tomorrow/It is 10.

It is like this. I don't know much about how to use Jinja, but I can calculate a little, so this may be good.

reference

http://stackoverflow.com/questions/19549980/short-form-for-string-format-locals

Recommended Posts

python variable expansion, format
Python string format
Python string format
format in python
Python variable length assignment?
Image format in Python
Python Pickle format notes
[Python] format methodical use
Easily format JSON in Python
Python indentation and string format
[Python 2/3] Parse the format string
Variable parameter expansion of bash
Format json with Vim (with python)
String format with Python% operator
[Python3] Format the character string using the variable name as the key.
Python
Expansion by argument of python dictionary
Python Application: Data Handling Part 3: Data Format
Automatically format Python code in Vim
[Python] Variable (definition, output, value change)
Handle NetCDF format data in Python
Handle GDS II format in Python
python datetime format quick reference table
[Python] Format when to_csv with pandas
Python memo using perl --format is convenient.
[Python] Get the variable name with str
[VScode] autopep8 format does not work [Python]
Various format specifications of str.format () method of Python3
Convert Python date types to RFC822 format
Python> Format specification when printing `%`> "% s% s"% ('Hello','World',)
[Introduction to Udemy Python3 + Application] 8. Variable declaration
Download files in any format using Python
Combine python function arguments into one variable
Differences in string processing between Python, Ruby, JS, PHP (combination and variable expansion)
Python> zip (* list4)> Matrix conversion> List and tuple argument expansion / dictionary argument expansion / local variable dictionary locals ()