File writing in Python 3.3 - python

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'

Related

Python-string formatting with variable length

I'm trying to pad dynamic elements within a table, but it seems as though the native padding function doesn't work with variables. Just wondering if I'm doing something wrong or if there are simple alternatives to center padding. I know of ljust and rjust but there is no m(iddle)just for some reason.
Simple example:
a=10
b='hi'
print(f'{b:^a}')
or
a=10
b='hi'
print('{:^a}'.format(b))
produces
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'a' for object of type 'str'
Typing 10 in place of a in the print statement makes it work as intended, so I'm guessing 'a' is being interpreted as a string by the string formatted. Is a helper function the only way out here?
In [114]: print(f'{b:^{a}}')
hi
In [115]: print(f'"{b:^{a}}"')
" hi "
Probably want to add another set of brackets
a=10
b='hi'
print(f'{b:^{a}}')

TypeError: findall() takes at least 2 arguments (1 given)

posted a much worse version of this question before. I've calmed down, refined my searches and I've almost figured out what I need. I'm trying to extract all the words ending in "ing" from a decently sized text file. Also, I'm supposed to be using regex but that has me incredibly confused, so at this point I'm just trying to get the results I need. here's my code:
import re
file = open('ing words.txt', 'r')
pattern = re.compile("\w+ing")
print re.findall(r'>(\w+ing<')
here's what I get:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-32-861693e3a217> in <module>()
3 pattern = re.compile("\w+ing")
4
----> 5 print re.findall(r'>(\w+ing<')
TypeError: findall() takes at least 2 arguments (1 given)
I'm still very new at this, and I don't know exactly why the second argument is needed (i know that the short answer is "because", but I'd like to know the theory if someone could take the time to explain it), but more-so how to add a second argument that won't break my code even further. I'm confident (but probably wrong) that after " print re.findall(r'>(\w+ing<') " I need some way of re-telling my terminal that it needs to search within that ing words.txt.
Am I even close?
re.findall() requires at least 2 arguments to be provided - a pattern itself and the string to search in. You though meant to use pattern.findall() instead:
print pattern.findall(r'>(\w+ing<')
You have to pass two arguments to re.findall() or call it as pattern method:
print pattern.findall(file.read())
print re.findall(r'>(\w+ing<', file.read())
or
for line in file:
print pattern.findall(file.read())
print re.findall(r'>(\w+ing<', line)
Suggestion: It's better to work with file by using With statement.
with open('ing words.txt', 'r') as file:
print pattern.findall(file.read())
print re.findall(r'>(\w+ing<', file.read())

How do you print two variables within brackets in Python 3?

I have this line of code:
print ("(x %s)(x %s)") % (var_p1, var_p2)
But it does not work, I am new to programming and I don't know what I have done wrong. Any experts out there with a simple answer?
I wanted it to randomly select an equation for a parabola. e.g. (x-3)(x+1) However, it comes up with the error message:
Traceback (most recent call last):
"File "E:/Python34/MyFiles/Math Study Buddy.py", line 26 in <module>
print ("(x %s)(x %s)") % (var_p1, var_p2)
TypeError: unsupported operand type (s) for %: 'NoneType' and 'tuple'
As you are in python 3 you need to put the variables inside the parenthesis after your string:
>>> print ("(x %s)(x %s)"%(2, 3))
(x 2)(x 3)
Note that in python 3 print is a function and you need to pass the string as its argument.So you can not put your variables outside the function!
For more detail read printf-style String Formatting
Note
The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer str.format() interface helps avoid these errors, and also provides a generally more powerful, flexible and extensible approach to formatting text.
You can use str.format
>>> var_p1 = 'test'
>>> var_p2 = 'test2'
>>> print(("(x {})(x {})".format(var_p1, var_p2)))
(x test)(x test2)
you don't need to use 'x' to substitude variables here.
This will fix:
print ("(%s)(%s)") % (var_p1, var_p2)
also, .format is better than %
see:
Python string formatting: % vs. .format

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.

Difference between using commas, concatenation, and string formatters in Python

I am learning python(2.7) on my own.
I have learned that we can use the following ways to put strings and variables together in printing:
x = "Hello"
y = "World"
By using commas:
print "I am printing" , x, y # I know that using comma gives automatic space
By using concatenation :
print "I am printing" + " " + x + " " + y
By using string formatters
print "I am printing %s %s" % (x, y)
In this case all three print the same:
I am printing Hello World
What is the difference between the three and are there any particular instances where one is preferred over the other?
To answer the general question first, you would use printing in general to output information in your scripts to the screen when you're writing code to ensure that you're getting what you expect.
As your code becomes more sophisticated, you may find that logging would be better than printing, but that's information for another answer.
There is a big difference between printing and the return values' representations that are echoed in an interactive session with the Python interpreter. Printing should print to your standard output. The echoed representation of the expression's return value (that show up in your Python shell if not None) will be silent when running the equivalent code in scripts.
1. Printing
In Python 2, we had print statements. In Python 3, we get a print function, which we can also use in Python 2.
Print Statements with Commas (Python 2)
The print statement with commas separating items, uses a space to separate them. A trailing comma will cause another space to be appended. No trailing comma will append a newline character to be appended to your printed item.
You could put each item on a separate print statement and use a comma after each and they would print the same, on the same line.
For example (this would only work in a script, in an interactive shell, you'd get a new prompt after every line):
x = "Hello"
y = "World"
print "I am printing",
print x,
print y
Would output:
I am printing Hello World
Print Function
With the built-in print function from Python 3, also available in Python 2.6 and 2.7 with this import:
from __future__ import print_function
you can declare a separator and an end, which gives us a lot more flexibility:
>>> print('hello', 'world', sep='-', end='\n****\n')
hello-world
****
>>>
The defaults are ' ' for sep and '\n' for end:
>>> print('hello', 'world')
hello world
>>>
2. String Concatenation
Concatenation creates each string in memory, and then combines them together at their ends in a new string (so this may not be very memory friendly), and then prints them to your output at the same time. This is good when you need to join strings, likely constructed elsewhere, together.
print('hello' + '-' + 'world')
will print
hello-world
Be careful before you attempt to join in this manner literals of other types to strings, to convert the literals to strings first.
print('here is a number: ' + str(2))
prints
here is a number: 2
If you attempt to concatenate the integer without coercing it to a string first:
>>> print('here is a number: ' + 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
This should demonstrate that you should only ever attempt to concatenate variables that are known to be strings. The new way of formatting demonstrated next handles this issue for you.
3. String Interpolation
The formatting you're demonstrating is the old style of string interpolation, borrowed from C. It takes the old string and one time creates a new one. What it does is fairly straightforward. You should use this when you may seem likely to building up a fairly large template (at 3+ lines and 3+ variables, you definitely should be doing it this way).
The new way of doing that would be to do this (using the index of the arguments):
print('I am printing {0} and {1}'.format(x, y))
or in python 2.7 or 3 (using the implied index):
print('I am printing {} and {}'.format(x, y))
or with named arguments (this is semantically easy to read, but the code doesn't look very DRY (i.e. Don't Repeat Yourself))
print('I am printing {x} and {y}'.format(x=x, y=y))
The biggest benefit of this over % style formatting (not demonstrated here) is that it lets you combine positional and keyword arguments
print('I am printing {0} and {y}'.format(x, y=y))
New in Python 3.6, format literals
Python 3.6 will have format literals, with a more elegant syntax (less redundancy). The simple syntax is something like:
print(f'I am printing {x} and {y}')
The format literals can actually execute code in-place:
>>> print(f'I am printing {"hello".capitalize()} and {"Wo" + "rld"}')
I am printing Hello and World
you should build list and use join with delimiter
for example
",".join(list_name)

Categories

Resources