Reputation: 25
I'm fairly new to coding, so this may seem like a bit of a silly question, however I am trying to print a 2d array grid and I'm not sure how I am supposed to do it. This is my code so far:
colA = [" ", " ", " ", " ", " "]
colB = [" ", " ", " ", " ", " "]
colC = [" ", " ", " ", " ", " "]
colD = [" ", " ", " ", " ", " "]
colE = [" ", " ", " ", " ", " "]
grid = [colA, colB, colC, colD, colE]
print("|"+[4,0]+"|"+[4,1]+"|"+[4,2]+"|"+[4,3]+"|"+[4,4]+"|")
print("|"+[3,0]+"|"+[3,1]+"|"+[3,2]+"|"+[3,3]+"|"+[3,4]+"|")
print("|"+[2,0]+"|"+[2,1]+"|"+[2,2]+"|"+[2,3]+"|"+[2,4]+"|")
print("|"+[1,0]+"|"+[1,1]+"|"+[1,2]+"|"+[1,3]+"|"+[1,4]+"|")
print("|"+[0,0]+"|"+[0,1]+"|"+[0,2]+"|"+[0,3]+"|"+[0,4]+"|")
It's basic, I know, but I just don't get it. When I try to print the grid, it comes up with this error message:
print("|"+[4,0]+"|"+[4,1]+"|"+[4,2]+"|"+[4,3]+"|"+[4,4]+"|")
TypeError: can only concatenate str (not "list") to str
What does this error message mean? Can I convert the 2d arrays into the strings they are in their respective lists without the console displaying something like: |[0,0]|[0,1]|[0,2]| etc.
Upvotes: 1
Views: 76
Reputation: 979
Here's a simple code snippet to display a 2-D matrix in a 'pretty' way:
arr = [[1,2,'3'], [4,5,'trampoline'], ['rf', 'th', 8.7]]
print("\n".join(str(row) for row in arr))
Output:
[1, 2, '3']
[4, 5, 'trampoline']
['rf', 'th', 8.7]
It's essentially doing the following -
[1, 2, '3'] + "\n" + [4, 5, 'trampoline'] + "\n" + ['rf', 'th', 8.7]
if you execute the above line, you'll get a similar error to the one you mentioned.
(TypeError: must be str, not list)
Notice the str(row)
in the code. By typecasting the list to a string, I am ensuring that concatenation happens between two string types only.
Upvotes: 1