Python Forum

Full Version: Understanding formatting
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi!

I found a script online that uses the website ipinfo.io to deliver some information about the users IP adress. I'm trying to figure out what this line means:
print ('IP : {4} \nRegion : {1} \nCountry : {2} \nCity : {3} \nOrg : {0}'.format(org,region,country,city,IP))
In context of this here script:

import re
import json
from urllib.request import urlopen

url = 'http://ipinfo.io/json'
response = urlopen(url)
data = json.load(response)

IP=data['ip']
org=data['org']
city = data['city']
country=data['country']
region=data['region']

print ('Your IP detail\n ')
print ('IP : {4} \nRegion : {1} \nCountry : {2} \nCity : {3} \nOrg : {0}'.format(org,region,country,city,IP))
Specifically, what exactly do the numbers represent inbetween the variables? How does the .format do its thing?

Thanks a lot in advance.
it gets better. if you have python 3.6 or newer loaded, you can use f-string.
print (f'IP : {IP} \nRegion : {region} \nCountry : {country} \nCity : {city} \nOrg : {org}')
You can do many things to further format the data, for example to print country in a 30 character field, and city in 20:
print(f'Country: {country:30} City: {city:20}')
rather than explain it all, here's a pretty good cheat sheet:
link: https://kapeli.com/cheat_sheets/Python_F...ents/index
Wow, that's exactly what I needed! Thanks a ton for that link, it does a great job at explaining what I wanted.
Hello,
numbers represent position of the variable in format() tuple. With using f strings, instead of numbers you could also enter variable names. There is a nice page on the subject on Python docs page. Here are examples for a quick glance.
Thank you very much, I'll take a look at the documentation, though it looks quite overwhelming for an amateur Python user. Thanks again!
Quote:though it looks quite overwhelming for an amateur Python user.
Not really, just look in the right column for what you want to do, then find the example in the left column
That comment was probably aimed at my link (Python docs), which when compared is a bit more involved.
Perhaps it is not the most suitable place to start learning about string formatting. But the content it is managable, if consumed at right pace.