Python 3.2 idle : how do I display two different values on same line?
team = ['sean', 'david', 'JK', 'KB', 'nina']
for i in team:
print(i), print(len(i))
Above shows following result:
sean
4
david
5
JK
2
KB
2
nina
4
but my ins开发者_JS百科truction book shows this:
sean 4
david 5
JK 2
KB 2
nina 4
how do I get "xxx, y" format? What am I doing wrong?
Try
for i in team:
print(i, len(i))
You want:
team = ['sean', 'david', 'JK', 'KB', 'nina']
for i in team:
print("%s, %d" % (i, len(i)))
By the way, there's no i
in team!
Just do this... nice and simple, no "string formatting" needed.
team = ['sean', 'david', 'JK', 'KB', 'nina']
for i in team:
print(i, len(i))
if you want comma between, then
team = ['sean', 'david', 'JK', 'KB', 'nina']
for i in team:
print(i, len(i), sep=', ')
I know this is late, but it's good for other people to see this by googling in the future...
Try
for i in team:
print "%s %s" % (i, len(i))
or:
for i in team:
print i + " " + str(len(i))
Also i think your original code must be :
for i in team:
print(i); print(len(i))
instead of :
for i in team:
print(i), print(len(i))
and if you want to do that with your code , try this :
for i in team:
print(i,end=','); print(len(i))
I believe your instruction book mentioned something like:
for i in team:
print i, len(i)
which gived the expected output in Python 2 but is no longer valid in Python 3.
The 'direct' replacement in Python 3 is:
for i in team:
print(i, len(i), sep=' ')
but you usually use something else like the %s %d
solution proposed above.
for i,j in zip(team,score):
print i,j
Output:
0 sean
1 david
2 JK
3 KB
4 nina
精彩评论