If my list in a text file has the following
I want it to print out like
However my current code prints it out like
My code is:
def addStudent(student):
reg,year,degree,*name= student.strip().split(" ")
name = list(reversed(name))
fullName = name[0] + ", " + " ".join(name[1:])
return (reg,year,degree,name,fullName)
def employee(employee):
reg,year,degree,*name,fullName = employe
print(format(fullName, "<32s")+format(reg,"<7d")+format(degree,">6s"),format(thisYear,">6s"))
How do i switch the order of the last two parts of the name? In which area is my code wrong because i'm not sure how else to reverse it. If i do add a print statement after the reversed function it does seperate each part of the name as a string, but when it joins, it does it in the wrong order
Just don't reverse the list:
def addStudent(student):
reg,year,degree,*name= student.strip().split()
fullName = "%s, %s" % (name[-1], " ".join(name[:-1]))
return (reg, year, degree, name, fullName)
Or change that line
fullName = name[0] + ", " + " ".join(name[1:])
to this
fullName = name[0] + ", " + " ".join(name[-1:0:-1])
Edit:
dat = '1234567 1 C100 Bartholomew Homer Simpson'
def addStudent(student):
reg,year,degree,*name= student.strip().split(" ")
name = list(reversed(name))
# You have now::
# name = ['Simpson', 'Homer', 'Bartholomew']
# Therefore , name[-1:0:-1]
# will select from last item in list 'Bartholomew to
# the 0th one, the 0th being excluded in reverse
fullName = name[0] + ", " + " ".join(name[-1:0:-1])
return (reg,year,degree,name,fullName)
def printStud(studentTuple):
reg,year,degree,*name,fullName = studentTuple
reg = int(reg)
thisYear = "Year "+str(year)
print(format(fullName, "<32s")+format(reg,"<7d")+format(degree,">6s"),format(thisYear,">6s"))
Output :
In [1]:
Simpson, Bartholomew Homer 1234567 C100 Year 1
If you need sorted names, you can sort them using sorted()
a=["metallica", "therion", "acdc"]
print a[0],", "+" ".join( sorted(a[1:]))
out:
metallica , acdc therion
Related
I need the print were words in my list are separated with space, but the result of my print is as follows
['Salt']
So it prints it as list with quotations :(
sry code is in Finnish :S
def poistaTuote(Tuotteet):
print("Ostoslistassasi on " + str(len(Tuotteet)) + " tuotetta.")
Index = int(input("Anna poistettavan tuotteen järjestysnumero: "))
Index = (Index)-1
for i in range(len(Tuotteet)):
if (Index == Tuotteet[i].index):
Index = i
if (Index == -1):
print("Indeksiä " + str(Index) + " ei löydy.")
print("Tuotteiden järjestysnumerot alkavat numerosta 1.")
else:
del Tuotteet[Index]
print("\nOstoslistasi sisältää seuraavat tuotteet:")
print(Tuotteet, end = " ")
return Tuotteet
Current output:
Ostoslistasi sisältää seuraavat tuotteet:
['Leipä', ' Leivän päälliset']
Desired output
Leipä Leivän päälliset
Spread the list elements as separate arguments to print:
print(*Tuotteet)
Or use str.join:
print(" ".join(Tuotteet))
I have a .txt file with the names and information as below
John, 87, 64, 72, 79, 81, Yes
Steve, 32, 45, 29, 37, 34, No
I am trying to read from the .txt file and number each name so that the specific name can be selected by entering the number and information from the selected name can be edited.
I want to be able to choose from two options "to edit one of the amounts" or "change from No to Yes"
line_count = 0
with open("results.txt", 'r') as r_file:
for line in r_file:
results_info = line.split(",")
line_count += 1
print("\n" + str(line_count) + " " + " Name:\t" + results_info[0]
+ "\n " + "Subject_1:\t " + results_info[1]
+ "\n " + "Subject_2:\t" + results_info[2]
+ "\n " + "Subject_3:\t" + results_info[3]
+ "\n " + "Subject_4:\t" + results_info[4]
+ "\n " + "Subject_5:\t" + results_info[5]
+ "\n " + "Pass?\t" + results_info[6])
student_select = input("\nEnter the number of the student to edit: ")
I've gotten this far but I am stuck when it comes to the rest.
edit:
Never added subject 5 to the code
I would like to write the changes made back to the .txt file
Sorry, I don't think that I was clear enough. I'd like to display the list of all the students numbered. From there give the option to select a student by entering their number and then the option to edit a grade or change pass to yes.
So you have 3 tasks here: read data, manage user input, save data if something has been modified.
And the best structure to handle this is a dict of lists (I kept to your idea of numbering the rows, but you could easily have the student's name as key instead). The code could be something like this (some more checks are needed on user input, of course):
def edit_info(fname):
#read data
with open(fname, 'r') as r_file:
info = {}
for i,line in enumerate(r_file):
info[str(i)] = line.rstrip().split(', ')
#prompt user and update data
dirty = False
while True:
for k,vl in info.items():
print(f'{k:2} {vl[0]:10} {" ".join(vl[1:-1])} {vl[-1]:3}')
student = input('Enter Student number or X to exit... ')
if student == 'X':
break
if student in info:
while True:
subject = input('Enter Subject number, P to set pass to yes, or X to stop editing... ')
if subject == 'X':
break
if subject == 'P':
info[student][-1] = 'Yes'
dirty = True
elif '1' <= subject <= str(len(info[student])-1):
subject = int(subject)
newvalue = input(
f'Enter new value for Student {student} for Subject {subject} (currently {info[student][subject]})... ')
info[student][subject] = newvalue
dirty = True
#save data if needed
if dirty:
with open(fname, 'w') as w_file:
for vl in info.values():
w_file.write(', '.join(vl)+'\n')
print('Completed')
I'm new to Python too so I will do it in a stupid way sorry. Here is my code which changes all the info of the nth student as all the input you made
def select_student_to_edit(input_num):
all_result=[]
result0 = input('Edit name element: ')
result1 = " " + input('Edit 1th element: ')
result2 = " " + input('Edit 2th element: ')
result3 = " " + input('Edit 3th element: ')
result4 = " " + input('Edit 4th element: ')
result5 = " " + input('Edit 5th element: ')
result6 = " " + input('Edit Yes/No element: ') + "\n"
with open('test1', 'r+') as f:
if input_num>1:
for i in range(1,input_num):
all_result.append(f.readline()) #If input_num = n then read n-1 line before, add all of the to a all_result list contain all lines
#Start modifying the line(student) that you want to:
results_info = f.readline().split(",") #Split all info into list to modify
results_info[0] = result0
results_info[1] = result1
results_info[2] = result2
results_info[3] = result3
results_info[4] = result4
results_info[5] = result5
results_info[6] = result6
all_result.append(",".join(results_info)) #add modified studen to all_result list
#Add all rest lines into all_result list
rest_line = f.readlines()
for line in rest_line:
all_result.append(line)
print(all_result)
#Write all line(student) in all_result into the old file
with open('test1','w+') as f:
for line in all_result:
f.write(line)
select_student_to_edit(int(input('Enter the student you want to change info (nth): ')))
I am trying to print out the phrase variable to the terminal using multiple strings. I am trying to replace one string with another string.
I don't know what to try to make sure the code will concatenate.
firstName = "jason", "jennifer"
LastName = "Maraz", "Lopez"
actor = firstName[0], LastName[0]
actress = firstName[1], LastName[1]
introduceActor= "hi my name is ".join(actor)
print (actor, actress)
s = "lucky"
t = "happy", "greatful", "nice"
phrase = "I am so " + str(s) + " see " + actor + " today. I am as " + str(s) + " as could be"
phrase = phrase.replace(str(s), str(t[1]))
phrase2 = introduceActor
print(phrase)
print(phrase2)
index = phrase.find("i")
print(index)
the error I got was:
File "/Users/zachary/Documents/code proejcts/Test.py", line 11, in <module>
phrase = "I am so " + str(s) + " see " + actor + " today. I am as " + str(s) + " as could be"
TypeError: can only concatenate str (not "tuple") to str
Your "actor" and "actress" are tuples that hold 2 strings each.
For your purpose, you should probably use:
actor = firstName[0] + LastName[0]
actress = firstName[1] + LastName[1]
That way, you will have strings instead of tuples. Check here for more information
I am a noob to python and am stuck on a simple task. I looked at similar questions on stackoverflow but was not able to apply to my own problem. I have created a file with a list of names. How do I create a new file where it reads the original file (pretending that I don't know how many names are in the file) and reverses the names (people are in same order but with last name before first name). Below is my script:
firstname1 = "Morty"
lastname1 = "Smith"
fullname1 = firstname1 + " " + lastname1
firstname2 = "Donna"
lastname2 = "Gueterman"
fullname2 = firstname2 + " " + lastname2
firstname3 = "Beth"
lastname3 = "Smith"
fullname3 = firstname3 + " " + lastname3
firstname4 = "Rick"
lastname4 = "Sanchez"
fullname4 = firstname4 + " " + lastname4
firstname5 = "Little"
lastname5 = "Dipper"
fullname5 = firstname5 + " " + lastname5
formal_names = fullname1,fullname2,fullname3,fullname4,fullname5
f = open("names_normal.txt","w")
f.write("%s " % (formal_names, ))
f.close()
def reverse_list(lst):
new = []
count = len(lst)-1
while count >=0:
new.append(lst[count])
count -= 1
return new
x = reverse_list(formal_names)
n = open("names_new.txt","w")
n.write("%s " % (x, ))
n.close()
These are my results:
1st file:
('Morty Smith', 'Donna Gueterman', 'Beth Smith', 'Rick Sanchez',
'Little Dipper')
2nd file: ('Little Dipper', 'Rick Sanchez', 'Beth Smith', 'Donna Gueterman', 'Morty Smith')
What I want: ('Smith Morty', 'Gueterman Donna', 'Smith Beth', 'Sanchez Rick', 'Dipper Little')
Any help would be appreciated! Thank you so much!
def reverse_list(lst):
new = []
for name in lst:
temp = name.split(" ")
new += [temp[1]+" "+temp[0]]
You're just changing order of words in the array, you should change order of the name and surname with splitting from space.
def reverse_name(name):
# Try to fill here and update if doesn't work
def reverse_list(lst):
new = []
for name in lst:
new.append(reverse_name(name))
return new
This is how I attacked this problem. It's probably best to put this in a function as mentioned above.
firstname1 = "Morty"
lastname1 = "Smith"
fullname1 = firstname1 + " " + lastname1
firstname2 = "Donna"
lastname2 = "Gueterman"
fullname2 = firstname2 + " " + lastname2
firstname3 = "Beth"
lastname3 = "Smith"
fullname3 = firstname3 + " " + lastname3
firstname4 = "Rick"
lastname4 = "Sanchez"
fullname4 = firstname4 + " " + lastname4
firstname5 = "Little"
lastname5 = "Dipper"
fullname5 = firstname5 + " " + lastname5
formal_names = [fullname1,fullname2,fullname3,fullname4,fullname5]
reversed = []
for i in range(0, (len(formal_names))):
rev = formal_names[i].split()
rev_name = rev[1] + ' ' + rev[0]
reversed.append(rev_name)
print(reversed)
['Smith Morty', 'Gueterman Donna', 'Smith Beth', 'Sanchez Rick', 'Dipper Little']
now you just write the list to a file
with open('output.txt', 'w') as file:
for name in reversed:
file.write(name)
You are complicating matters using separate variables for each person's name. In Python the better way of handling this is to use one of python's data structures, in this case a list with each name contained in a tuple. The advantage of doing this is that you can iterate over the list and refer to parts of the name by position, for example: names[0][1] for "Smith".
names = [("Morty","Smith"),
("Donna","Gueterman"),
("Beth","Smith"),
("Rick","Sanchez"),
("Little","Dipper")]
Or, if you wish you can used a namedtuple to make things clear, especially if you add other data items for each person.
import collections
Person = collections.namedtuple('Person', 'first last')
names = [Person("Morty","Smith"),
Person("Donna","Gueterman"),
Person("Beth","Smith"),
Person("Rick","Sanchez"),
Person("Little","Dipper")]
The output can then be created with a list comprehension :
normal = ", ".join([name.first + " " + name.last for name in names])
reversed = "; ".join([name.last + ", " + name.first for name in names])
print(normal)
print(reversed)
You can alter the punctuation : the first string ", " is between names, the second string " " is between words. Then, use the method suggested in earlier answers to store the strings in a file.
(I would advise using punctuation between last and first otherwise you can run into problems with names like "Alan Simon".)
In my Code below I am having issues with 2 things. For one The math in the function on lines 40 (examPoints) and 47 (hwkPoints) is being passed a range of values in a list on line 94. It should be taking the scores and adding them up but for some reason it isn't adding the last number on each range passed.
ex: for myValues[11:13] it is being passed the numbers 75, 95, and 97 but it only adds the first 2 and not the last.
My code is here:
from time import asctime
from time import localtime
def findGrade(myGrade): #argument number in range of 1 - 100 or float myNum?
if myGrade >= 90:
letterGrade = "A"
if myGrade >= 80:
letterGrade = "B"
if myGrade >= 70:
letterGrade = "C"
if myGrade >= 60:
letterGrade = "D"
if myGrade < 60:
letterGrade = "F"
return letterGrade
def calculatePointsEarned(hwkGrades, examGrades):
hwkTotal = float(hwkPoints(hwkGrades))
#print hwkTotal
examTotal = float(examPoints(examGrades))
#print examTotal
myAverage = (hwkTotal + examTotal) / possiblePoints
myAverage = myAverage * 100.0
#myAverage = int(myAverage)
return myAverage
def totalPoints(hwkGrades, examGrades):
hwkTotal = int(hwkPoints(hwkGrades))
examTotal = int(examPoints(examGrades))
allPoints = str((hwkTotal + examTotal))
return allPoints
#Create newtimeline using day of week, space, month, space, day, space, year, space time from asctime function
def timeMessage():
localtime()
newTimeline = asctime()
return newTimeline
def examPoints(examValues):
myGrades = 0
for grade in examValues:
myGrades = int(grade) + myGrades
#print str(myGrades) + " exam\n"
return myGrades
def hwkPoints(hwkValues):
myGrades = 0
for grade in hwkValues:
myGrades = int(grade) + myGrades
#print str(myGrades) + " hwk"
return myGrades
def requestMessage (myValues, myTime):
nameLine = myValues[1] + ", " + myValues[2] + "\t" + myValues[0] + "\t" + myValues[3]
examScore = "Exam " + "- " + myValues[11] + ", " + myValues[12] + ", " + myValues[13]
hwkScore = "Homework " + "- " + myValues[4] + ", " + myValues[5] + ", " + myValues[6] + ", " + myValues[7] + ", " + myValues[8] + ", " + myValues[9] + ", " + myValues[10]
pointsEarned = "Total points earned " + "- " + totalPoints(myValues[4:10], myValues[11:13])
myGrade = "Grade: " + str(theAverage) + " that is a " + findGrade(theAverage)
message = nameLine + "\n" + examScore + "\n" + hwkScore + "\n" + pointsEarned + "\n" + myGrade + "\n" + myTime
return message
def fileOutput(studentID, lastName, firstName, dateTime):
myLine = studentID + " " + lastName + ", " + firstName + " " + dateTime + "\n"
return myLine
#Create input stream from grades.dat and assign to infile
inFile = open('grades.dat', "r")
#Create output stream to results.dat and assign to outfile
outFile = open('results.dat', 'w+')
myTime = timeMessage()
theAverage = 0
theLettergrade = ""
theMessage = ""
possiblePoints = 550
theRequest = ""
studentID = raw_input("Please input student ID: ")
myLine = "notemptystring"
while myLine != "": #may be wrong Is myline not equal to the empty string?
myLine = inFile.readline() #may be wrong Read line from infile and assign to myline
myLine = myLine.strip('\r\n')
myValues = myLine.split(",") #Separate values in myline and assign to myvalues
if studentID == myValues[0]:
#print myValues
#Call calculatePointsEarned function with a list of homework values and a list of exam values and assign to theaverage
theAverage = calculatePointsEarned(myValues[4:10], myValues[11:13])
#print theAverage
theLettergrade = findGrade(theAverage) #Call findGrade function with theaverage and assign to thelettergrade)
#print theLettergrade
#Call fileOutput function with studentid, lastname, firstname, and datetime to get message for writing to output file, and assign to therequest
theRequest = fileOutput(myValues[0], myValues[1], myValues[2], timeMessage())
#print theRequest
theMessage = requestMessage(myValues, timeMessage()) #Call requestMessage with myline and mytime for message to display, and assign to themessage
#Write theRequest to outfile
outFile.write(theRequest)
print theMessage
else: #is studentid not equal to first element in myValues
"Do Nothing"
#close infile and outfile
inFile.close()
outFile.close()
Edit: Sorry for the link I was having problems getting the code to look right on here.
for myValues[11:13] it is being passed the numbers 75, 95, and 97 but it only adds the first 2 and not the last
myValues[11:13] selects two elements, not three. The end index (13) is not included in the range.
Have a read of Explain Python's slice notation