Ok...so, it's kind of easy.
The old method:
num = 6
mystr = 'number is %s' % num
print(mystr) # number is 6
The newer .format method:
num = 6
mystr = "number is {}".format(num)
print(mystr) # number is 6
The .format method using named variable (useful for when sequence can't be depended upon):
num = 6
mystr = "number is {num}".format(num=num)
print(mystr) # number is 6
The shorter f-string method: (thank you @mayur)
num = 6
mystr = f"number is {num}"
print(mystr) # number is 6
Answer from skeetastax on Stack OverflowVideos
Ok...so, it's kind of easy.
The old method:
num = 6
mystr = 'number is %s' % num
print(mystr) # number is 6
The newer .format method:
num = 6
mystr = "number is {}".format(num)
print(mystr) # number is 6
The .format method using named variable (useful for when sequence can't be depended upon):
num = 6
mystr = "number is {num}".format(num=num)
print(mystr) # number is 6
The shorter f-string method: (thank you @mayur)
num = 6
mystr = f"number is {num}"
print(mystr) # number is 6
In each of your cases you have a str object. Its .format method returns the formatted string as a new object. Its __mod__ method, which python calls when it sees the % operator, also returns a formatted string.
Functions and methods return anonymous objects. The context where they are called decide what happens next.
"number is {num}".format(num=num)
throws the result away.
some_variable = "number is {num}".format(num=num)
assigns the result.
some_function("number is {num}".format(num=num))
calls the function with the result as a parameter. print is not a special case - python doesn't do anything special with print.
Interestingly, f-strings like f"number is {num}" is compiled into a series of instructions that build the string dynamically.
Python 3.6+ does have variable interpolation - prepend an f to your string:
f"foo is {bar}"
For versions of Python below this (Python 2 - 3.5) you can use str.format to pass in variables:
# Rather than this:
print("foo is #{bar}")
# You would do this:
print("foo is {}".format(bar))
# Or this:
print("foo is {bar}".format(bar=bar))
# Or this:
print("foo is %s" % (bar, ))
# Or even this:
print("foo is %(bar)s" % {"bar": bar})
Python 3.6 will have has literal string interpolation using f-strings:
print(f"foo is {bar}.")
Modules don't share namespaces in python, so globals() for my_print is always going to be the globals() of my_print.py file ; i.e the location where the function was actually defined.
def mprint(string='', dic = None):
dictionary = dic if dic is not None else globals()
print string.format(**dictionary)
You should pass the current module's globals() explicitly to make it work.
Ans don't use mutable objects as default values in python functions, it can result in unexpected results. Use None as default value instead.
A simple example for understanding scopes in modules:
file : my_print.py
x = 10
def func():
global x
x += 1
print x
file : main.py
from my_print import *
x = 50
func() #prints 11 because for func() global scope is still
#the global scope of my_print file
print x #prints 50
Part of your problem - well, the reason its not working - is highlighted in this question.
You can have your function work by passing in globals() as your second argument, mprint('Hello my name is {name}',globals()).
Although it may be convenient in Ruby, I would encourage you not to write Ruby in Python if you want to make the most out of the language.
Python 3.6 will add literal string interpolation similar to Ruby's string interpolation. Starting with that version of Python (which is scheduled to be released by the end of 2016), you will be able to include expressions in "f-strings", e.g.
name = "Spongebob Squarepants"
print(f"Who lives in a Pineapple under the sea? {name}.")
Prior to 3.6, the closest you can get to this is
name = "Spongebob Squarepants"
print("Who lives in a Pineapple under the sea? %(name)s." % locals())
The % operator can be used for string interpolation in Python. The first operand is the string to be interpolated, the second can have different types including a "mapping", mapping field names to the values to be interpolated. Here I used the dictionary of local variables locals() to map the field name name to its value as a local variable.
The same code using the .format() method of recent Python versions would look like this:
name = "Spongebob Squarepants"
print("Who lives in a Pineapple under the sea? {name!s}.".format(**locals()))
There is also the string.Template class:
tmpl = string.Template("Who lives in a Pineapple under the sea? $name.")
print(tmpl.substitute(name="Spongebob Squarepants"))
Since Python 2.6.X you might want to use:
"my {0} string: {1}".format("cool", "Hello there!")