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.
Related
This question already has answers here:
python - how to apply backspaces to a string [closed]
(2 answers)
Closed 1 year ago.
As a simple use case in Python, I wish to convert some encoded text and set it equal to a variable or dictionary key as would be printed on screen. This issue came about by piping some std out to memory from a command line function where some of the text didn't seem to be properly interpreted in python.
Example:
myVar = "N\x08NA\x08AM\x08ME\x08E"
print(myVar)
="NAME"
When myVar is input as a dictionary key, I get the following result:
myDict = {}
myDict[myVar] = 'foobar'
print(myDict.keys())
=dict_keys(['N\x08NA\x08AM\x08ME\x08E'])
How can I make myDict.keys() = dict_keys(['Name'])?
Same question for a variable where
myVar = "NAME"
rather than 'N\x08NA\x08AM\x08ME\x08E'
I've tried variants of myVar.encode() and str(myVar) with no success.
You can easily remove every character that would be erased by a backspace (\x08 or \b) with a regular expression.
import re
re.sub('.\x08', '', "N\x08NA\x08AM\x08ME\x08E")
='NAME'
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"))])
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 3 years ago.
I'm coding a little game and I want a score system. I have two variables that I want to display as "The current score is: X/X" but its not including the variables
I've tried putting it in 'quotes' put it didn't work
U = 2
L = 3
print("Current score: U/L")
I want it to be "Current score: 2/3"
print(f"Current score: {U}/{L}")
Strings enclosed with simple quotes or double-quotes imply that all characters in it are just literal text - they are not interpreted as variables.
From Python 3.6, the prefix f for the quotes delimiting the string denotes an special literal which can include Python expressions inside - including variables. Still, to separate these variables from plain text (and avoid unpredictable substitutions), these expressions have to be further delimited by { }, inside the string.
Prior to Python 3.6, one would have to do it in two separate steps: create a plain string with special markers were the variables contents would be inserted, and then call the .format method on the string. (or, there is an older method using the % operator instead). Fully documenting these other methods would be long - but a short form would require one to write:
print("Current score: {}/{}".format(U, L))
This question already has an answer here:
Why doesn't the result from sys.stdin.readline() compare equal when I expect it to?
(1 answer)
Closed 6 years ago.
Im new to this so Im sorry if this isn't the best way to ask the question...
here is the code -
import sys
print("What is ur name?")
name = sys.stdin.readline()
answer = "jack"
if name is answer :
print("ur awesome")
exit();
right now when I run it in cmd I don't get anything printed even though
I input - jack? thank you in advance
Firstly, replace is with ==. is checks whether the two underlying strings are the same entity (in memory) whereas == just wants to check if they have the same value.
Because the source of "jack" is coming from two sources (one from the user, another hard-coded by you) they are two seperate objects.
As #dawg mentioned you also have to use the .strip() to get rid of the newline when using sys.stdin.readline() for input. The best way to read input is to use the input() method in python3, or raw_input() in python2.
name = input('What is your name?\n')
Use == for string comparison. Also, readline() will include the newline at the end of the string. You can strip it with e.g.
name = name.strip()
Alternatively, you can use raw_input() (input() in python 3) instead of readline(), as it will not include the newline to begin with.
name = raw_input("What is your name?\n")
It's helpful to be able to print a string to see if it has any extra whitespace, e.g.
print("name: [%s]\n" % name)
This question already has answers here:
String format with optional dict key-value
(5 answers)
Closed 7 years ago.
What str.format does almost exactly I'm looking for.
A functionality I would like to add to format() is to use optional keywords and for that I have to use another special character (I guess).
So str.format can do that:
f = "{ID1}_{ID_optional}_{ID2}"
f.format(**{"ID1" : " ojj", "ID2" : "makimaki", "ID_optional" : ""})
# Result: ' ojj__makimaki' #
I can't really use optional ID's. If the dictionary does not contain "ID_optional" it produces KeyError. I think it should be something like this to mark the optional ID:
f = "{ID1}_[IDoptional]_{ID2}"
Another thing: I have lot of template strings to process which are use [] rather than {}. So the best way would be to add the special characters as an argument for the format function.
So the basic question is there a sophisticated way to modify the original function? Or I should write my own format function based on str.format and regular expressions?
One option would be to define your own Formater. You can inherit the standard one and override get_field to return some reasonable default for your use case. See the link for some more documentation.
You if/else and format based on whether the dic has the key or not:
f = "{ID1}_{ID_optional}_{ID2}" if "ID_optional" in d else "{ID1}_{ID2}"
A dict lookup is 0(1) so it is cheap just to check