简体   繁体   中英

How to remove brackets in python with string?

I have this program:

import sys
students = []
grades = []

while True:
    student = input ("Enter a name: ").replace(" ","")
    if  student.isalpha() == True and student != "0":
        while True:
            grade = input("Enter a grade: ").replace(" ","")
            if grade == "0" or grade == 0:
                print ("\n")
                print ("A zero is entered.")
                sys.exit(0)
            if grade.isdigit()== True: 
                grade = int(grade)
                if grade >= 1 and grade <= 10:
                    if student in students:
                        index = students.index(student)
                        grades[index].append(grade)
                        break
                    else:
                        students.append(student)
                        grades.append([grade])
                        break
                else:
                    print("Invalid grade.")
    elif student == "0": 
        print("A zero is entered.")
        break
    else:
        print ("Invalid name.")
for i in range(0,len(students)): 
    print("NAME: ", students[i])
    print("GRADE: ", grades[i])
    print("AVERAGE: ", round(sum(grades[i])/len(grades[i]),1), "\n")

I need to make the [] disappear between numbers when the program prints them, for example.

When you enter numbers, like this:

Enter a name: Jack
Enter a grade: 8
Enter a name: Jack
Enter a grade: 9
Enter a name: Jack
Enter a grade: 7
Enter a name: 0
A zero is entered.

It prints like this:

NAME:  Jack
GRADE:  [8, 9, 7]
AVERAGE:  8.0 

But I need the program to print like this:

 NAME:  Jack
 GRADE:  8, 9, 7
 AVERAGE:  8.0 

The grades should be without brackets. I think I need to use string or something, does anyone know how?

strip可让您从开头和结尾删除指定的字符。

str(grades[i]).strip('[]')

如果grades是整数列表的列表:

print(', '.join(str(i) for i in grades[g])) # where g sublist index

First:

>>> grades = [[1,2,3],[4,5,6]]

Now you have a few choices:

>>> print("GRADE:", *grades[0])
GRADE: 1 2 3

or:

>>> print("GRADE:", ', '.join(map(str, grades[0])))
GRADE: 1, 2, 3

or, in a script or block:

print("GRADE: ", end='')
print(*grades[0], sep=', ')

result of above:

GRADE: 1, 2, 3

Replace [0] with [i] as needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM