First off, here's the code. (Still new in function creating)
Function Testing!!
def UserInfo(name, age, birth):
"""Read this by doing UserInfo__doc__"""
print("Name:",name)
print("Age:",age)
print("Birth:",birth)
return
n_input=input("Name?>> ")
a_input=int(input("Age?>> "))
b_input=input("Birth date?(MM DD YYYY)>> ")
UserInfo(n_input, a_input, b_input)
CodeOutput
('name:', 'Jaymz')
('age:', 25)
('birth:', '02 26 1991')
The int portion of the code outputs no " ' " (which I knew) but still with "()" and ","...
The string portion outputs all the stuff I don't want surrounding my output...
How would you get rid of that in your code?(I learn by seeing other code first on how people do it)
ps. Brainfart?.... Do I have to do a "format" on the output code? or is format only for numbers?
you get this output because you're using python 2.x. Python 2 thinks you're printing a tuple. Python 3 would issue what you want.
As jojonas suggested, using from __future__ import print_function also works for all versions. You're not able to use print without parentheses after importing that, which is for the best.
But ...
To treat all cases, use format instead (using {} to indicate the location of the string to insert):
def UserInfo(name, age, birth):
"""Read this by doing UserInfo__doc__"""
print("Name: {}".format(name))
print("Age: {}".format(age))
print("Birth: {}".format(birth))
Note: this also works but is not as powerful:
print("Name: "+name) # would need `str` for integer, ex `str(age)`
print("Name: %s" % name) # old-style formatting
Related
I am trying to do something that should be very simple. I am a bit frustrated for why my code won't work, so any help is appreciated :).
My program reads in data, and then makes a dictionary that records the number of times a particular item occurs (I am using Twitter data and counting hashtag occurrences). I want to output the top tweets, and have found a nice easy way to do that using the following:
def main():
tweet_file = open(sys.argv[1])
tweet_dic = lines(tweet_file) #function that makes my dictionary
for i in range(0,10):
big_key = max(tweet_dic, key = lambda i: tweet_dic[i])
big_value = tweet_dic[big_key]
sys.stdout = big_key + " " + str(big_value)
del tweet_dic["big_key"]
tweet_file.close()
The error I get on using this is AttributeError: 'str' object has no attribute 'write'
Now I have outputted the two different values into terminal using print just fine, they can be put in two different print statements with no problems since I don't have to concatenate or anything. I have checked the two variables types, and as expected they are always str & int.
My understanding of the str(integer to convert) function is that you should be able to pass in an integer and get a string representation back! After it has been converted, I have been able to print out things like this in the past with no issues.
Things to consider that may be throwing it out - the big_key can sometimes be a string that was converted from Unicode by .encode('utf-8'). Otherwise the output from my file (printing on separate lines) looks like:
MTVHottest 60
KCAMexico 38
EXO 26
CD9 24
Unicode 19
Coders 18
AlonsoVillapandoTrendy 17
Unicode 14
Unicode 14
Any ideas? Thanks in advance!
The error you're getting is because of this: https://docs.python.org/2/library/sys.html#sys.stdout
stdout and stderr needn’t be built-in file objects: any object is acceptable as long as it has a write() method that takes a string argument.
stdout and stderr are the locations where the data is written, you aren't supposed to assign data itself to stdout, which is what it looks like you're doing.
As others have mentioned you would assign stdout to where you want and then use the print command to actually get the data to go there. But if all you're trying to do is print a line of text to a file then why not just open the file and write to it normally?
with open(tweet_file, 'w') as f:
f.write(big_key + " " + str(big_value))
The specific error you're getting is from the line:
sys.stdout = big_key + " " + str(big_value)
This is not how things are output to stdout.
Using a print would be the appropriate way to do that:
print(big_key + " " + str(big_value))
There are some other strange things in your code example, like for example using big_key and then "big_key" in quotes. So probably that's not the end of your bugs and errors.
I am attempting to make a dictionary into a formatted string and then write it to a file, however my entire formatting seems to be incorrect. I'm not sure how to debug since all my tester cases are given different files. I was able to use the interactive mode in python to find out what my function is actually writing to the file, and man is it so wrong! Can you help me correctly format?
Given a sorted dictionary, I created it into a string. I need the function to return it like so:
Dictionary is : {'orange':[1,3],'apple':[2]}
"apple:\t2\norange:\t1,\t3\n"
format is: Every key-value pair of the dictionary
should be output as: a string that starts with key, followed by ":", a tab, then the integers from the
value list. Every integer should be followed by a "," and a tab except for the very last one, which should be followed by a newline
Here is my function that I thought would work:
def format_item(key,value):
return key+ ":\t"+",\t".join(str(x) for x in value)
def format_dict(d):
return sorted(format_item(key,value) for key, value in d.items())
def store(d,filename):
with open(filename, 'w') as f:
f.write("\n".join(format_dict(d)))
f.close()
return None
I now have too many tabs on the last line. How do I edit the last line only out of the for loop?
ex input:
d = {'orange':[1,3],'apple':[2]}
my function gives: ['apple:\t2', 'orange:\t1,\t3']
but should give: "apple:\t2\norange:\t1,\t3\n"
Adding the newline character to the end of the return statement in format_item seems to yield the correct output.
return key+ ":\t"+",\t".join(str(x) for x in value) + '\n'
In [10]: format_dict(d)
Out[10]: ['apple:\t2\n', 'orange:\t1,\t3\n']
The purpose of this script is to parse a text file (sys.argv[1]), extract certain strings, and print them in columns. I start by printing the header. Then I open the file, and scan through it, line by line. I make sure that the line has a specific start or contains a specific string, then I use regex to extract the specific value.
The matching and extraction work fine.
My final print statement doesn't work properly.
import re
import sys
print("{}\t{}\t{}\t{}\t{}".format("#query", "target", "e-value",
"identity(%)", "score"))
with open(sys.argv[1], 'r') as blastR:
for line in blastR:
if line.startswith("Query="):
queryIDMatch = re.match('Query= (([^ ])+)', line)
queryID = queryIDMatch.group(1)
queryID.rstrip
if line[0] == '>':
targetMatch = re.match('> (([^ ])+)', line)
target = targetMatch.group(1)
target.rstrip
if "Score = " in line:
eValue = re.search(r'Expect = (([^ ])+)', line)
trueEvalue = eValue.group(1)
trueEvalue = trueEvalue[:-1]
trueEvalue.rstrip()
print('{0}\t{1}\t{2}'.format(queryID, target, trueEvalue), end='')
The problem occurs when I try to print the columns. When I print the first 2 columns, it works as expected (except that it's still printing new lines):
#query target e-value identity(%) score
YAL002W Paxin1_129011
YAL003W Paxin1_167503
YAL005C Paxin1_162475
YAL005C Paxin1_167442
The 3rd column is a number in scientific notation like 2e-34
But when I add the 3rd column, eValue, it breaks down:
#query target e-value identity(%) score
YAL002W Paxin1_129011
4e-43YAL003W Paxin1_167503
1e-55YAL005C Paxin1_162475
0.0YAL005C Paxin1_167442
0.0YAL005C Paxin1_73182
I have removed all new lines, as far I know, using the rstrip() method.
At least three problems:
1) queryID.rstrip and target.rstrip are lacking closing ()
2) Something like trueEValue.rstrip() doesn't mutate the string, you would need
trueEValue = trueEValue.rstrip()
if you want to keep the change.
3) This might be a problem, but without seeing your data I can't be 100% sure. The r in rstrip stands for "right". If trueEvalue is 4e-43\n then it is true the trueEValue.rstrip() would be free of newlines. But the problem is that your values seem to be something like \n43-43. If you simply use .strip() then newlines will be removed from either side.
My application offers the ability to the user to export its results. My application exports text files with name Exp_Text_1, Exp_Text_2 etc. I want it so that if a file with the same file name pre-exists in Desktop then to start counting from this number upwards. For example if a file with name Exp_Text_3 is already in Desktop, then I want the file to be created to have the name Exp_Text_4.
This is my code:
if len(str(self.Output_Box.get("1.0", "end"))) == 1:
self.User_Line_Text.set("Nothing to export!")
else:
import os.path
self.txt_file_num = self.txt_file_num + 1
file_name = os.path.join(os.path.expanduser("~"), "Desktop", "Exp_Txt" + "_" + str(self.txt_file_num) + ".txt")
file = open(file_name, "a")
file.write(self.Output_Box.get("1.0", "end"))
file.close()
self.User_Line_Text.set("A text file has been exported to Desktop!")
you likely want os.path.exists:
>>> import os
>>> help(os.path.exists)
Help on function exists in module genericpath:
exists(path)
Test whether a path exists. Returns False for broken symbolic links
a very basic example would be create a file name with a formatting mark to insert the number for multiple checks:
import os
name_to_format = os.path.join(os.path.expanduser("~"), "Desktop", "Exp_Txt_{}.txt")
#the "{}" is a formatting mark so we can do file_name.format(num)
num = 1
while os.path.exists(name_to_format.format(num)):
num+=1
new_file_name = name_to_format.format(num)
this would check each filename starting with Exp_Txt_1.txt then Exp_Txt_2.txt etc. until it finds one that does not exist.
However the format mark may cause a problem if curly brackets {} are part of the rest of the path, so it may be preferable to do something like this:
import os
def get_file_name(num):
return os.path.join(os.path.expanduser("~"), "Desktop", "Exp_Txt_" + str(num) + ".txt")
num = 1
while os.path.exists(get_file_name(num)):
num+=1
new_file_name = get_file_name(num)
EDIT: answer to why don't we need get_file_name function in first example?
First off if you are unfamiliar with str.format you may want to look at Python doc - common string operations and/or this simple example:
text = "Hello {}, my name is {}."
x = text.format("Kotropoulos","Tadhg")
print(x)
print(text)
The path string is figured out with this line:
name_to_format = os.path.join(os.path.expanduser("~"), "Desktop", "Exp_Txt_{}.txt")
But it has {} in the place of the desired number. (since we don't know what the number should be at this point) so if the path was for example:
name_to_format = "/Users/Tadhg/Desktop/Exp_Txt_{}.txt"
then we can insert a number with:
print(name_to_format.format(1))
print(name_to_format.format(2))
and this does not change name_to_format since str objects are Immutable so the .format returns a new string without modifying name_to_format. However we would run into a problem if out path was something like these:
name_to_format = "/Users/Bob{Cat}/Desktop/Exp_Txt_{}.txt"
#or
name_to_format = "/Users/Bobcat{}/Desktop/Exp_Txt_{}.txt"
#or
name_to_format = "/Users/Smiley{:/Desktop/Exp_Txt_{}.txt"
Since the formatting mark we want to use is no longer the only curly brackets and we can get a variety of errors:
KeyError: 'Cat'
IndexError: tuple index out of range
ValueError: unmatched '{' in format spec
So you only want to rely on str.format when you know it is safe to use. Hope this helps, have fun coding!
I searched but found many things for removing space. I'm brand spanking new to python and trying to write a simple program that asks for first name, last name and then does the greeting. No matter how many spaces I put in between name + last on the print function line it keeps mashing the first and last name together.
name = input ("What is your first name?: ")
last = input ("what is your last name?: ")
print ('Nice to meet you,' name + last)
It outputs:
What is your first name?:Jessie
What is your last name?: Jackson
Nice to meet you, JessieJackson
What am I doing wrong?
There are several ways to get the wanted output:
Concentrating strings
If you want to concentrate your string you use the + operator.
It will concentrate your strings EXACTLY the way you provide them in your code.
Example:
>>> stringA = 'This is a'
>>> stringB = 'test'
>>> print(stringA + stringB)
'This is atest'
>>> print(stringA + ' ' + stringB)
'This is a test'
Printing on the same line
If you simply want to print multiple strings on the same line you can provide your strings to the print function as arguments seperated with a ,
Example:
>>> print('I want to say:', stringA, stringB)
I want to say: This is a test
Formatting strings
The most used way is string formatting. This can be done in two ways:
- Using the format function
- Using the 'old' way with %s
Example:
>>> print('Format {} example {}'.format(stringA, stringB))
Format This is a example test
>>> print('Old: %s example %s of string formatting' % (stringA, stringB))
Old: This is a example test of string formatting
Of course those examples can be combined in any way you want.
Example:
>>> stringC = 'normally'
>>> print((('%s strange {} no one ' % stringA) + stringC).format(stringB), 'uses')
This is a strange test no one normally uses
You can use + to append a string literal containing a space like this:
print ('Nice to meet you, ' + name + ' ' + last)
If you don't need to concatenate them together you could use:
print("Nice to meet you, " name, last)
outputting:
Nice to meet you, Jessie Jackson
This is because + concatenates strings but , prints them on the same line, but automatically spacing them because they are seperate entities.