[Tutor] Question About the .format Method.
Bryon Adams
bryonadams at openmailbox.org
Wed Nov 9 17:30:20 EST 2016
Hello,
Working on a simple function to get an IP address and make it look
pretty for the PyNet course. I'm wondering if there's way to evenly
space text with the string.format() method similar to how I'm doing it
with the % operator. The last two prints keep everything left aligned
and 20 spaces wide. Is there a way to accomplish this with the .format()
method that I use in the first print function?
# Getting the IP address and putting it into list
ip4 = input('Please enter a /24 network address: ')
ip4 = ip4.split('.') # Split string into a list
ip4 = ip4[:3] # Force list to be a /24 network address
ip4.append('0')
print('{}.{}.{}.{}'.format(ip4[0], ip4[1], ip4[2], ip4[3]))
ip4_str = '.'.join(ip4)
ip4_bin = bin(int(ip4[0]))
ip4_hex = hex(int(ip4[0]))
# Printing the table
print('\n'+'---------------------------------------------------------')
print('%-20s %-20s %-20s' %('NETWORK_NUMBER', 'FIRST_OCTET_BINARY',
'FIRST_OCTET_HEX'))
print('%-20s %-20s %-20s' %(ip4_str, ip4_bin, ip4_hex))
PS. I realise the first print can be simplified with a .join but I
forgot about .join and left it to help illustrate my question.
Thanks,
Bryon
More information about the Tutor
mailing list