Formatting lists in Python

python list
python format
python print format
print list of lists python
python print list elements
python list to string
format precision python
python print format list of strings

I am very new to coding, and I am trying to create a project that lists grade percentages along with their letter equivalents. I am having a lot of trouble formatting it to look nice, though. This is most of the code I currently have:

(Edited to show more data)

def main():
    grade_list = create_grades()
    print_list(grade_list)

def create_grades():
    grade_list = []
    for student in range(35):
        percentage_grade = round(random.uniform(50, 100), 2)
        letter_grade = get_grade(percentage_grade)
        dumb_tuple = (percentage_grade, letter_grade)
        grade_list.append(dumb_tuple)

list_title = "Grades for Class With a Cool Name"
def print_list(grade_list):
    print(list_title)
    print("{:20}".format("Grade Percentage"), "Letter Grade")
    for student in grade_list:
        print('{:10}'.format(student[0]), "{:>17}".format(student[1]))

and this is the resulting output:

Grades for Class With a Cool Name
Grade Percentage     Letter Grade
     93.44                 A
     99.58                 A
     67.37                D+
     79.07                C+
     64.75                 D
     79.42                C+
      97.2                 A
     73.37                 C
     86.33                 B
     83.56                 B
     98.89                 A
     68.74                D+
     76.03                 C
     63.75                 D
     77.43                C+
     51.32                 F
     53.18                 F
     61.56                D-
      65.4                 D
     94.48                 A
     85.96                 B
     92.62                A-
     90.51                A-
      91.7                A-
     50.76                 F
     67.93                D+
     52.98                 F
     81.85                B-
     60.91                D-
     84.71                 B
     63.74                 D
     61.64                D-
     74.21                 C
     97.99                 A
     72.95                C-

All I am trying to accomplish now is to make the letters line up, rather than having them become a jagged line when there is a plus or minus added to the value. I know this may seem like a relatively simple question, but none of my google research has helped me much, as I don't understand a lot of code yet. Any responses help.


If you don't want to use any other libraries, there is a pretty simple solution.

Update your print statement like this:

print('{:10}'.format(student[0]), "{:>17}".format(student[1][0]), "{:<1}".format(student[1][1:]))

and you'll get output like:

Grades for Class With a Cool Name
Grade Percentage     Letter Grade
jeff                       A +
sally                      A
tim                        B -

This works by splitting your student[1] value (the grade) into two pieces. First, student[1][0] gets the letter and we right justify it with the same spacing you had. Next, we will pull off the plus/minus if it exists with student[1][1:]. This is a slice which goes from index 1 to the end. If index 1 is the non-inclusive end, then this slice is "empty" so nothing happens.

EDIT: To remove spaces, you can put the {} items in one statement and separate the arguments with commas:

print('{:10}'.format(student[0]), "{:>17}{:<1}".format(student[1][0], student[1][1:]))

In Python, is there an elegant way to print a list in a custom format , Python | Ways to format elements of given list. Method #1 : Using List comprehension. Method #2 : Using Map. Method #3 : Using format. Method #4 : Using Iteration. You should take a look to the format method of python. You could then define your formatting string like this : >>> s = '{0} BLAH BLAH {1} BLAH {2} BLAH BLIH BLEH' >>> x = ['1', '2', '3'] >>> print s.format(*x) '1 BLAH BLAH 2 BLAH 3 BLAH BLIH BLEH'


If pandas is ok with you:

import pandas as pd
df = pd.DataFrame(grade_list, columns=['Grade Percentage', 'Letter Grade'])
print(list_title)
print(df)

Python, Printing a list in python can be done is following ways: Using for loop : Traverse from 0 to len(list) and print all elements of the list one by one uisng a for loop, this � An alternative style of formatting lists in Python source code. Python Tutorial: String Formatting - Advanced Operations for Dicts, Lists, Numbers, and Dates - Duration: 13:53. Corey Schafer


Using the code suggested, my updated formatting looks like this:

def print_list(grade_list):
    print(list_title)
    print("{:20}".format("Grade Percentage"), "Letter Grade")
    for student in grade_list:
        print('{:10}'.format(student[0]), "{:>17}{:>1}".format(student[1][0], student[1][1:]))

and this is my new output:

Grades for Class With a Cool Name
Grade Percentage     Letter Grade
     98.99                 A 
     65.17                 D 
     68.71                 D+
     78.15                 C+
     85.97                 B 
     91.48                 A-
     57.61                 F 
      73.5                 C 
     70.06                 C-
     75.54                 C 
     50.14                 F 
     59.78                 F 
     80.49                 B-
      67.5                 D+
     90.99                 A-
     59.28                 F 
     50.37                 F 
     52.03                 F 
     60.42                 D-
     60.38                 D-
     81.54                 B-
     92.49                 A-
     55.96                 F 
     73.52                 C 
     85.03                 B 
     80.36                 B-
      80.4                 B-
      71.8                 C-
     81.64                 B-
     58.89                 F 
     67.06                 D+
     79.22                 C+
     50.72                 F 
     64.91                 D 
     84.82                 B 

Thanks for the help! My code is working perfectly now and I don't have to obsess over that little formatting error.

Print lists in Python (4 Different Ways), How to use string formatting with lists in Python. Use %s. Use str.format(). Formatting a list to a string converts each item in the list to a formattable value. Python format function allows printing an integer in the hex style. The symbol ‘x’ or ‘X’ after the colon inside the parenthesis notifies to display a number in hex format. >>> print (' {0:x}'.format (10)) a >>> >>> >>> print (' {0:X}'.format (10)) A.


How to use string formatting with lists in Python, With new style formatting it is possible (and in Python 2.6 even mandatory) to give containers that support __getitem__ like for example dictionaries and lists: . String functions let you easily format your output in specific ways. Type the following code into the notebook and click Run Cell. print' '.join (Colors)) Python provides more than one way to perform any task. In this case, the code uses the join () method to join the newline character with each member of Colors.


PyFormat: Using % and .format() for great good!, Type the following code into the notebook and click Run Cell. print('First: {0}\ nSecond: {1'.format(*Colors)). In this case, the output is formatted in� Binary format:c: Converts the value into the corresponding unicode character:d: Try it: Decimal format:e: Try it: Scientific format, with a lower case e:E: Try it: Scientific format, with an upper case E:f: Try it: Fix point number format:F: Try it: Fix point number format, in uppercase format (show inf and nan as INF and NAN):g: General format:G


Printing Lists Using Python, In this Python tutorial, we will be learning how to perform some String Formatting - Advanced Duration: 13:53 Posted: Mar 10, 2016 The string format () method formats the given string into a nicer output in Python. The syntax of format () method is: template.format (p0, p1,, k0=v0, k1=v1,) Here, p0, p1, are positional arguments and, k0, k1, are keyword arguments with values v0, v1, respectively.