Python Forum

Full Version: misunderstanding of format in print function
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,
I'm using Python 3.7.0 32-bit and wanted to print some variables with the format syntax
The variables are :
client_address: ('192.168.167.200', 49706)
message['FrameNumber']: 396
The code:
print('Accepted new connection from {}:{} {}'.format(*client_address,client_address[1],message['FrameNumber']))
gives the result :
Output:
Accepted new connection from 192.168.167.200:49706 49706
Why is there 2 times the value 49706 ?

while in two lines the result is what I expected :
print('Accepted new connection from {}:{}'.format(*client_address,client_address[1]))
print('frame:{}'.format(message['FrameNumber']))
Output:
Accepted new connection from 192.168.167.200:49706 frame:396
Because you unpack and have four values which will not fit into three placeholders so the last one will be skipped. Observe:

>>> client_address = ('192.168.167.200', 49706) 
>>> message = 396                                                                          
>>> print(*client_address, client_address[1], message)                                     
192.168.167.200 49706 49706 396
In two lines you skip the third value in first line. So if you look for solution skip 'client_address[1]' in your original code and everything should be fine.
*client_address unpacks the tuple into its individual elements. This way format(*client_address,client_address[1],message['FrameNumber']) is same as format('192.168.167.200', 49706, 49706, 396)
You have just 3 placeholders thus the last element (396) is simply ignored

when on 2 lines it just ignores the second 49706.

In other words, change your code to .format(*client_address, message['FrameNumber'])