Python Forum
Understanding formatting
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Understanding formatting
#1
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.
Reply
#2
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
Reply
#3
Wow, that's exactly what I needed! Thanks a ton for that link, it does a great job at explaining what I wanted.
Reply
#4
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.
Reply
#5
Thank you very much, I'll take a look at the documentation, though it looks quite overwhelming for an amateur Python user. Thanks again!
Reply
#6
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
Reply
#7
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.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020