Reputation: 41
I am currently trying to print a list of objects where each new line gets a number infront of it. Like the first line has a 1 infront of it, the second has a 2 etc. The print function works fine when I am not using the numbers for each line.
I tried to write it:
n=0
for x in List:
print("\n".join(str(n,x))
n+=1
The List in this case contains a bunch of objects, all having 4 attributes, self.name, self.randomint, self.randomint2, self.randomint3
But I am getting an invalid syntax doing this, would appreciate help!
Upvotes: 0
Views: 1553
Reputation: 1124110
You missed a closing parenthesis:
print("\n".join(str(n,x))
# --------^
but that's not a correct statement still as str()
takes one string argument with optional encoding.
It'll be easier to use enumerate()
to add a count, and pass in two arguments to print()
:
for n, x in enumerate(Line):
print(n, x)
Upvotes: 1
Reputation: 369364
The parentheses are unbalanced in the following line:
print("\n".join(str(n,x))
Replace it with:
print("\n".join(str(n,x)))
# ^
Another issue: str
accepts only one argument.
>>> str(1, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: str() takes at most 1 argument (2 given)
>>> str(1)
'1'
Complete example code:
n=0
for x in List:
print(n, x)
n += 1
using enumerate
:
for n, x in enumerate(List, 1):
print(n, x)
Upvotes: 2