misunderstanding of format in print function - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: misunderstanding of format in print function (/thread-22093.html) |
misunderstanding of format in print function - Harvey - Oct-29-2019 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']: 396The code: print('Accepted new connection from {}:{} {}'.format(*client_address,client_address[1],message['FrameNumber']))gives the result : 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']))
RE: misunderstanding of format in print function - perfringo - Oct-29-2019 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 396In 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. RE: misunderstanding of format in print function - buran - Oct-29-2019 *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']) |