What's wrong with the following two lines [duplicate] - python

This question already has answers here:
How do I escape curly-brace ({}) characters in a string while using .format (or an f-string)?
(23 answers)
Closed 7 years ago.
I am trying to write a piece of python code which will write a piece of CMake code ...
But when I get to the following phase:
def_desc = "blaa"
s = " FILE(WRITE ${CONFIG_H} \"/* {0} */\\n\")\n".format(def_desc)
then python yells at me:
Traceback (most recent call last):
File "/home/ferencd/tmp/blaa.py", line 2, in <module>
s = " FILE(WRITE ${CONFIG_H} \"/* {0} */\\n\")\n".format(def_desc)
KeyError: 'CONFIG_H'
[Finished in 0.0s with exit code 1]
I understood that somehow the interpreter thinks that {CONFIG_H} is supposed to mean a parameter from the parameter list of format ... but no, I'd really like to print out that into the output ... as it is.
How can I deal with this situation?

You need to escape brackets "}" if it uses not for format variable.
def_desc = "blaa"
s = " FILE(WRITE ${{CONFIG_H}} \"/* {0} */\\n\")\n".format(def_desc)

you need to use double braces:
s = " FILE(WRITE ${{CONFIG_H}} \"/* {0} */\\n\")\n".format(def_desc)
It is much easier, though, to use template library for stuff like this, like jinja or mako.

Related

How do I write a concatenated string to a file? [duplicate]

This question already has answers here:
How to redirect 'print' output to a file?
(15 answers)
Closed 2 years ago.
So I have this piece of code here
#inside of a repeating "while loop"
print(even,flush=True, end=inbetween) #inbetween is what's between each number. (space, new line, etc.)
even=even+2
Which prints out a sequence of even numbers in my number generator
(https://github.com/JasonDerulo1259/JasonsGenerator)
The issue I have with it is that When I do f.write to write the result It says that I am not allowed to write something with multiple arguements. What is the work-around for this?
(here's the syntax error that shows)
File "main.py", line 34, in massprint
f.write(even,flush=True, end=inbetween)
TypeError: write() takes no keyword arguments
Also, If i try put even,flush=True, end=inbetween inside of a variable, I get this syntax error no matter how I change it.
File "main.py", line 32
placeholdervar=[even,flush=True, end=inbetween]
^
SyntaxError: invalid syntax
"Just do print(even,flush=True, end=inbetween, file=f)
– Tomerikoo"
And to print to file and console. Just add another without 'file=f'

Python f-string name "blabla is not defined" error when trying to insert a string into string [duplicate]

This question already has answers here:
How do I escape curly-brace ({}) characters in a string while using .format (or an f-string)?
(23 answers)
Closed 2 years ago.
Okay, so to start off I am trying to insert a string into code that I made into string.
Here's what I mean:
x="achievement"
data= f"{x}_scores:[{ score: { type: number}},"
Trying to insert x into the the string using f-string.
But it keeps saying
NameError: name 'score' is not defined
This is a test I'm doing for a bigger project.
Note that the string I'm inserting into is code I turned into string because I need to insert 100+ words into similar strings, and I can't do it by hand. I'm just trying to generate a list and copy and paste the output elsewhere.
I absolutely need to insert it into that format. Can I get some help?
Here is how:
x = "achievement"
data = f"{x}_scores:""[{score: { type: number}},"
print(data)
Output:
achievement_scores:[{score: { type: number}},
The "" I inserted in between {x}_scores: and [{score: { type: number}}, tells python to only perform the f on the first half of the string, and then append the second half after the evaluation.

Input quote, output in caps, lower case and reverse [duplicate]

This question already has answers here:
input() error - NameError: name '...' is not defined
(15 answers)
Closed 7 years ago.
I'm trying to make a program in Python 3 (IDLE) which lets the user input a quote and outputs it in upper case, lower case and in reverse. I've tried this:
quote = input("Enter your quote here: ")
print(quote.upper())
print(quote.lower())
print(quote.reverse())
...but all I get back when I test it is this error text:
Enter your quote here: You are always unique.
Traceback (most recent call last):
File "C:\Users\shobha m nair\Documents\Quote Conversion.py", line 2, in <module>
quote = input("Enter your quote here: ")
File "<string>", line 1
You are always unique.
^
SyntaxError: invalid syntax
You are probably using Python 2.x that's why you got the unexpected behaviour. The following code ran fine with Python 3.5:
quote = input("Enter your quote here: ")
print(quote.upper())
print(quote.lower())
print(quote[::-1])
There is no "reverse" method for strings.
This works for me:
quote = input("Enter your quote here: ")
print(quote.upper())
print(quote.lower())
print(quote[::-1])
The last one is the extended splice operator. AFAIK there's no reverse method in Python 3.

Python - .format with {} touching other characters [duplicate]

This question already has answers here:
Str.format() for Python 2.6 gives error where 2.7 does not
(2 answers)
Closed 8 years ago.
I am trying to use the ".format" with a string to insert values in a for loop. This is what I'm trying to do:
with open('test.txt', 'w') as fout:
for element in range (0, 5):
line1 = 'Icon_{}.NO = Icon_Generic;'.format(element)
fout.write(line1)
When I do this it chokes. My best guess is that it doesn't like the underscore directly beside the {} ("_{}"). Is this correct? Is there a good workaround for this?
I have used something like this and it works:
line1 = Icon_Generic.NO = Icon_%02d.NO;\n' % element
However, if I want to do a large multiline bunch of code using the "% element" doesn't work well.
Thanks in advance!
EDIT: As best I can tell I'm using Python 3.3
This is the error I get (using IDLE 3.3.2 shell):
>>> with open('p_text.txt', 'w') as fout:
for element in range(0, 5):
template = """if (!Icon_{0}.notFirstScan) {""".format(element)
fout.write(template)
fout.write('\n\n')
input('press enter to exit')
Traceback (most recent call last):
File "<pyshell#13>", line 3, in <module>
template = """if (!Icon_{0}.notFirstScan) {""".format(element)
ValueError: Single '{' encountered in format string
It's the final opening brace that's given you the problem, as indicated by the error message: a "Single '{' encountered". If you need literal curly braces in the formatted string, you must escape them by doubling up ('{{') wherever you mean them to be literals:
template = """if (!Icon_{0}.notFirstScan) {{""".format(element)
^ escape the literal '{'
Note that this is true for closing curly braces (}) as well!
>>> print('{{{0}}}'.format('text within literal braces'))
{text within literal braces}

Why does python use both " " and ' ' to make a string literal [duplicate]

This question already has answers here:
Single quotes vs. double quotes in Python [closed]
(19 answers)
Closed 9 years ago.
Python's Philosophy:
....
Simple is better than complex.
....
So why does it use both double quote " " and single quote ' ' to indicate something is a string literal.
I was lost when I typed:
x = "aa"
x
And saw:
'aa'
But not:
"aa"
When I saw the above philosophy, I doubted it. It needs some explanations.
This isn't complex at all. In fact, it's rather helpful.
Both '' and "" can be used in python. There's no difference, it's up to you.
In your example, when you type x, you are given the representation of the string (i.e, it's equivalent to print repr(x)). It wouldn't have mattered if you did x = 'aa'
I like to use either for cases such as:
print 'Bill said, "Hey!"'
print "I'm coming!"
If we used " for the first example, then there would be an error because Python would interpret it as "Bill said, ".
If we used ' for the second example, then there would be an error because Python would interpret it as 'I'
Of course, you could just escape the apostrophes, but beautiful is better than ugly.
You can use "" to be able to write "I'm legend" for example.

Categories

Resources