I'm having an issue trying to modify strings within a list. I have a for loop set up to select each string item but I'm not able to modify it. I thought it might be a global/local scope issue or a muteable/immutable type issue but I've looked through documentation and I can't find out why I wouldn't be able to modify the string with the code I have in place right now.
The little program is not complete but the idea is to take my tableData variable and print it to look like
apples Alice dogs
oranges Bob cats
cherries Carol moose
banana David goose
This is a problem I've been on for a combined 5 hours, and its from Automate the Boring Stuff with Python chapter 6 practice project found at: https://automatetheboringstuff.com/chapter6/
Here is my code (issue being at the very bottom):
# This program will take a list of string lists and print a table of the strings.
from copy import deepcopy
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
def print_table():
'''This function will take any list of lists and print it in a table format
with evenly spaced columns.'''
# First I wanted to identify the max length of my columns without making changes to my original list
copied_list = deepcopy(tableData)
for copied_innerlist in range(len(copied_list)):
copied_list[copied_innerlist].sort(key=len, reverse=True) # sort each inner list by length
colWidths = [len(copied_innerlist[0]) for copied_innerlist in copied_list] # change the column width variable to reflect the length of longest string in each inner list
# Now that I've stored my columns widths I want to apply them to all the strings without affecting the original
final_list = deepcopy(tuple(tableData))
for item in range(len(final_list)):
for inner_item in final_list[item]:
inner_item = inner_item.rjust(colWidths[item])
'''WHY WONT THIS RJUST METHOD STICK '''
print(final_list)
"""this just looks like that original list! :( """
print_table()