Reputation: 5760
I'm very new to Python and working with an existing python script, presently it outputs a message with a variable tagged on the end:
print "ERROR: did not find any details inside \"{0}".format(filename)
I want to modify this adding in another variable so the output reads:
print "ERROR: did not find \"{name}\" inside \"{file}\""
Where {name} and {file} are replaced with the variables, what is the correct way to achieve this?
Upvotes: 0
Views: 457
Reputation: 177685
In Python 2, you can use format
to pass named parameters and it plugs the names into the variables. Note you can quote strings with single quotes or double quotes, so you can prevent having to escape double quotes by using single quotes:
>>> name = 'John'
>>> file = 'hello.txt'
>>> print 'ERROR: did not find "{name}" inside "{file}"'.format(name=name,file=file)
ERROR: did not find "John" inside "hello.txt"
A shortcut for this is to use the **
operator to pass a dictionary of key/value pairs as parameters. locals()
returns all the local variables in this format, so you can use this pattern:
>>> name = 'John'
>>> file = 'hello.txt'
>>> print 'ERROR: did not find "{name}" inside "{file}"'.format(**locals())
ERROR: did not find "John" inside "hello.txt"
Python 3.6+ makes this cleaner with f-strings:
>>> name = 'John'
>>> file = 'hello.txt'
>>> print(f'ERROR: did not find "{name}" in "{file}"')
ERROR: did not find "John" in "hello.txt"
Upvotes: 2
Reputation: 85
.format is a very useful method in python. Check this link for better understanding. https://www.w3schools.com/python/ref_string_format.asp I hope the examples will help you understand the method well.
You can also try this:
print "ERROR: did not find \"{}\" inside \"{}\"".format(name, file)
Upvotes: 1
Reputation: 157
f"ERROR: did not find \{name}\ inside \{file}\"
If you need to encapsulate the variables, you just need to put f
which means format string so that instead of just printing it out it inserts the value of the variable.
Upvotes: 0
Reputation: 15009
You seem to be using Python 2, so the correct way would be like:
print "ERROR: did not find \"{0}\" inside \"{1}\"".format(name, file)
{0}
means to take the first argument from the format()
argument list and so on.
Moving to Python 3 and f-strings
is preferable, all other things being equal.
Upvotes: 1