Strings with embedded variables in Python -


maybe asked didn't find , wanted know how embed variables string in python. this:

print('hi, name %s , age %d' %(name, age)) 

but confusing , ruby this

puts('hi, name #{name} , age #{age}') 

is there way in python in ruby?

from python 3.6 onwards, can use formatting string literal (aka f-strings), takes valid python expression inside {...} curly braces, followed optional formatting instructions:

print(f'hi, name {name} , age {age:d}') 

here name , age both simple expressions produce value name.

in versions preceding python 3.6, can use str.format(), paired either locals() or globals():

print('hi, name {name} , age {age}'.format(**locals())) 

as can see format rather close ruby's. locals() , globals() methods return namespaces dictionary, , ** keyword argument splash syntax make possible str.format() call access names in given namespace.

demo:

>>> name = 'martijn' >>> age = 40 >>> print('hi, name {name} , age {age}'.format(**locals())) hi, name martijn , age 40 

note explicit better implicit , should pass in name , age arguments:

print('hi, name {name} , age {age}'.format(name=name, age=age) 

or use positional arguments:

print('hi, name {} , age {}'.format(name, age)) 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -