Python print output containing two variables? - python

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?

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"

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.

.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)

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.

Related

Store formatted strings, pass in values later?

I have a dictionary with a lot of strings.
Is it possible to store a formatted string with placeholders and pass in a actual values later?
I'm thinking of something like this:
d = {
"message": f"Hi There, {0}"
}
print(d["message"].format("Dave"))
The above code obviously doesn't work but I'm looking for something similar.
You use f-string; it already interpolated 0 in there. You might want to remove f there
d = {
# no f here
"message": "Hi There, {0}"
}
print(d["message"].format("Dave"))
Hi There, Dave
Issue: mixing f-String with str.format
Technique
Python version
f-String
since 3.6
str.format
since 2.6
Your dict-value contains an f-String which is immediately evaluated.
So the expression inside the curly-braces (was {0}) is directly interpolated (became 0), hence the value assigned became "Hi There, 0".
When applying the .format argument "Dave", this was neglected because string already lost the templating {} inside. Finally string was printed as is:
Hi There, 0
Attempt to use f-String
What happens if we use a variable name like name instead of the constant integer 0 ?
Let's try on Python's console (REPL):
>>> d = {"message": f"Hi There, {name}"}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'name' is not defined
OK, we must define the variable before. Let's assume we did:
>>> name = "Dave"; d = {"message": f"Hi There, {name}"}
>>> print(d["message"])
Hi There, Dave
This works. But it requires the variable or expression inside the curly-braces to be valid at runtime, at location of definition: name is required to be defined before.
Breaking a lance for str.format
There are reasons
when you need to read templates from external sources (e.g. file or database)
when not variables but placeholders are configured independently from your source
Then indexed-placeholders should be preferred to named-variables.
Consider a given database column message with value "Hello, {1}. You are {0}.". It can be read and used independently from the implementation (programming-language, surrounding code).
For example
in Java: MessageFormat.format(message, 74, "Eric")
in Python: message.format(74, 'Eric').
See also:
Format a message using MessageFormat.format() in Java

Any way to use variable values in a string literal?

I'm using python to generate LaTeX code (long story - I need to produce 120-odd unique exams).
This means that I have lots of strings that have \ or { or } etc. So I'm making them literals. However, I also want to have Python calculate numbers and put them in. So I might have a string like:
r"What is the domain of the function $\exp{-1/(VARIABLE - x^2+y^2)}$?" which I want to write to a file. But I want VARIABLE to be a random numerical value. The question isn't how to calculate VARIABLE, but rather is there a clean way to put VARIABLE into the string, without something like:
r"What is the domain of the function $\exp{-1/(" + str(VARIABLE) + r"- x^2+y^2)}$?"
I'm going to be doing this a lot, so if it's doable, that would be great. I've got Python 3.5.2.
Python still supports the string substitution operator %:
r"What is ... $\exp{-1/(%s - x^2+y^2)}$?" % str(VARIABLE)
You can be more specific if you know the type of the variable, e.g.:
r"What is ... $\exp{-1/(%f - x^2+y^2)}$?" % VARIABLE
More than one variable can be substituted at once:
r"$\mathrm{x}^{%i}_{%i}$" % (VAR1, VAR2)
This will work as long as your strings do not have LaTeX comments that, incidentally, also begin with a %. If that's the case, replace % with %%.
You may be able to use the % formatting
variable = 10
"What is the domain of the function $exp{-1/x + %d}." % (variable)
I'm very partial to f-strings, since the variable names appear where the values eventually will.
You can have raw f-strings, but you'll need to escape curly braces by doubling them ({{), which could get confusing if you're writing out complex LaTex.
To get the string What is ... $\exp{-1/(10 - x^2+y^2)}$?:
VARIABLE = 10
rf"What is ... $\exp{{-1/({VARIABLE} - x^2+y^2)}}$?"
If your goal is to not break up the string you could do this to replace the variable with your variable value and also be able to use %s in your string:
r"What is the domain of the function $\exp{-1/(VARIABLE - x^2+y^2)}$?".replace("VARIABLE", str(VARIABLE))
If you need multiple values you can use this:
variable_list = [2, 3]
''.join([e+str(variable_list[c]) if c<len(variable_list) else str(e) for c,e in enumerate(r"What is the domain of the function $\exp{-1/(VARIABLE - x^2+y^2)}$?".split("VARIABLE"))])

why are attributes passed as strings in getattr()?

When printing the value of a variable, you don't add quotations around the variable but when using the getattr() function to access the value of an attribute you pass it as a string. Is there a reason for this or is it something I just have to remember?
That is the purpose of getattr. That way you can access attributes dynamically, based on a string stored in memory.
Example scenario:
user_provided_input = input()
getattr(some_object, user_provided_input + "dummy")
If the user typed "justa" this would be exactly the same as:
some_object.justadummy
You can also use strings that usually would cause a syntax error or some other kind of error if used as a string literal as well:
>>> setattr(some_object, ".", "dummyvalue")
>>> getattr(some_object, ".")
'dummyvalue'
>>> some_object..
File "<stdin>", line 1
some_object..
^
SyntaxError: invalid syntax

how can i make {0} and {1} variables in python? [duplicate]

This question already has answers here:
How do I put a variable’s value inside a string (interpolate it into the string)?
(9 answers)
Closed 4 years ago.
in C# it was Possible to Use a Code Like This:
Console.WriteLine ("hello{0}" ,Hello);
i Want to do Same Thing in Python,i Want to Call Variable With {0} and {1} Way.
How Can I Do This ?
You can use format for the same
"hello {0}".format("Hello")
You can use the str.format function:
"Hello {0} {1}".format(firstname, lastname)
You can also leave the space in between the {} blank to automatically pick the next argument:
>>> "{}, {}".format("one", "two")
one, two
You can also use a prettier "f string" syntax since python 3.6:
f"Hello{Hello}"
The variable inside the {} will be looked up and placed inside the code.
You can use place holders to format strings in Python. So in this example, if you want to use a place holder such as {0}, you have to use a method called .format in Python. Below is a mini example.
name = input('Please enter your name: ')
with open('random_sample.txt', 'w') as sample:
sample.write('Hello {0}'.format(name))
As you can see, I ask the user for a name and then store that name in a variable. In my string that I write to a txt file, I use the place holder, and outside of the string I use the .format method. The argument that you enter will be the variable that you want to use.
if you want to add another variable {1} you would do this:
sample.write('Hello {0}. You want a {1}').format(name, other_variable))
so whenever you use a placeholder like this in Python, use the .format() method. You will have to do additional research on it because this is just a mini example.

Replacing a substring of a string with Python

I'd like to get a few opinions on the best way to replace a substring of a string with some other text. Here's an example:
I have a string, a, which could be something like "Hello my name is $name". I also have another string, b, which I want to insert into string a in the place of its substring '$name'.
I assume it would be easiest if the replaceable variable is indicated some way. I used a dollar sign, but it could be a string between curly braces or whatever you feel would work best.
Solution:
Here's how I decided to do it:
from string import Template
message = 'You replied to $percentageReplied of your message. ' +
'You earned $moneyMade.'
template = Template(message)
print template.safe_substitute(
percentageReplied = '15%',
moneyMade = '$20')
Here are the most common ways to do it:
>>> import string
>>> t = string.Template("Hello my name is $name")
>>> print t.substitute(name='Guido')
Hello my name is Guido
>>> t = "Hello my name is %(name)s"
>>> print t % dict(name='Tim')
Hello my name is Tim
>>> t = "Hello my name is {name}"
>>> print t.format(name='Barry')
Hello my name is Barry
The approach using string.Template is easy to learn and should be familiar to bash users. It is suitable for exposing to end-users. This style became available in Python 2.4.
The percent-style will be familiar to many people coming from other programming languages. Some people find this style to be error-prone because of the trailing "s" in %(name)s, because the %-operator has the same precedence as multiplication, and because the behavior of the applied arguments depends on their data type (tuples and dicts get special handling). This style has been supported in Python since the beginning.
The curly-bracket style is only supported in Python 2.6 or later. It is the most flexible style (providing a rich set of control characters and allowing objects to implement custom formatters).
There are a number of ways to do it, the more commonly used would be through the facilities already provided by strings. That means the use of the % operator, or better yet, the newer and recommended str.format().
Example:
a = "Hello my name is {name}"
result = a.format(name=b)
Or more simply
result = "Hello my name is {name}".format(name=b)
You can also use positional arguments:
result = "Hello my name is {}, says {}".format(name, speaker)
Or with explicit indexes:
result = "Hello my name is {0}, says {1}".format(name, speaker)
Which allows you to change the ordering of the fields in the string without changing the call to format():
result = "{1} says: 'Hello my name is {0}'".format(name, speaker)
Format is really powerful. You can use it to decide how wide to make a field, how to write numbers, and other formatting of the sort, depending on what you write inside the brackets.
You could also use the str.replace() function, or regular expressions (from the re module) if the replacements are more complicated.
Checkout the replace() function in python. Here is a link:
http://www.tutorialspoint.com/python/string_replace.htm
This should be useful when trying to replace some text that you have specified. For example, in the link they show you this:
str = "this is string example....wow!!! this is really string"
print str.replace("is", "was")
For every word "is", it would replace it with the word "was".
Actually this is already implemented in the module string.Template.
You can do something like:
"My name is {name}".format(name="Name")
It's supported natively in python, as you can see here:
http://www.python.org/dev/peps/pep-3101/
You may also use formatting with % but .format() is considered more modern.
>>> "Your name is %(name)s. age: %(age)i" % {'name' : 'tom', 'age': 3}
'Your name is tom'
but it also supports some type checking as known from usual % formatting:
>>> '%(x)i' % {'x': 'string'}
Traceback (most recent call last):
File "<pyshell#40>", line 1, in <module>
'%(x)i' % {'x': 'string'}
TypeError: %d format: a number is required, not str

Categories

Resources