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

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}

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'

File writing in Python 3.3

Can anyone give me advice on writing in files. This is in python 3.3. This error message just keeps on popping up.
Traceback (most recent call last):Line 28, in file.write(name_1,"and",name_2,"have a",loveness_2,"percent chance of falling in love") TypeError: write() takes exactly 1 argument (6 given)
And my code is this:
if vowels_1 > vowels_2:
loveness = vowels_2/vowels_1
loveness_2 = loveness * 100
print("It is ",loveness_2,"% possible of you falling in love")
print("*********************************************")
file.write("*********************************************")
file.write(name_1,"and",name_2,"have a",loveness_2,"percent chance of
falling in love")
file.write is not the same as print; as the error says, it only takes a single argument. You need to compose your string before passing it to that call.
One way to do that is with string formatting:
line = "{} and {} have a {} percent chance of falling in love".format(name_1, name_2, loveness_2)
file.write(line)
A comma separates arguments, so the interpreter thinks you're giving a bunch of arguments here. If you want to do a string concatenation, use '+'.
print('a' + 'b')
>>> 'ab'
A more pythonic way would be to use .format()
print('{} some text {}'.format('foo', 'bar')
>>>'foo some text bar'

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.

What's wrong with the following two lines [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 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.

TypeError: expected a character buffer object ITS SO ANNOYING

This is what it says on the interpreter...
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
nth_term_rule(list_a)
File "C:\Users\Jimmy\Desktop\Python 2.7 Functions Pack 1\nth_term_rule.py", line 5, in nth_term_rule
f.write(n)
TypeError: expected a character buffer object
This is really bugging me, I'm currently in the middle of the nth term rule function for my function pack and I'm attempting to make sure the sequence is steady - if not the nth term rule would be wrong. So I'm trying to append a text file that will have every number in the list in it. Then the interpreter will go through each number, making sure the difference between it and the next one is the same as difference as the previous numbers.
Unfortunately it comes up with the error above and I don't know why.
Here is my code if it helps...
def nth_term_rule(a):
for n in a:
str(n)
f = open("C:\Users\Jimmy\Desktop\Python 2.7 Functions Pack 1\Numbers.txt","a")
f.write(n)
f.close()
if a[0] - a[1] == a[len(a)-2] - a[len(a)-1]:
b=a[1] - a[0]
c=a[0] - b
return (b,'n + ',c)
else:
return ("Error.")
Any help would be much appreciated.
You are ignoring the return value of str():
str(n)
str() returns the new string, you want to assign this back to n:
n = str(n)
You probably want to avoid re-opening the file each loop iteration; just open it once:
filename = r"C:\Users\Jimmy\Desktop\Python 2.7 Functions Pack 1\Numbers.txt"
with open(filename, "a") as f:
for n in a:
f.write(str(n) + \n)
This adds a few more things:
Using the file as a context manager (with the with statement) makes sure that it is closed again automatically, when the block ends.
Using a raw string literal (r'...') prevents \ being interpreted as an escape sequence. That way filenames that start with a t or n or r, etc. are not interpreted as special. See string literals for more info.
I assumed you probably wanted to have newlines between your values when written to the file.

Categories

Resources