Python Forum
Not understanding the use of {0:25} and {1:3}
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Not understanding the use of {0:25} and {1:3}
#1
I was working through a book on machine learning and came across this snippet of code.
import mglearn import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn.datasets import fetch_lfw_people people = fetch_lfw_people(min_faces_per_person=20, resize = 0.7) image_shape = people.images[0].shape counts = np.bincount(people.target) for i, (count,name) in enumerate(zip(counts, people.target_names)): print("{0:25} {1:3}".format(name, count), end=' ') if (i+1)% 3 == 0: print()
I'm not sure what is the use of {0:25} and {1:3} in the second last print function. I have not seen this before.
Thanks.
Reply
#2
(Mar-02-2022, 12:27 PM)yang19177 Wrote: I'm not sure what is the use of {0:25} and {1:3} in the second last print function
It's string formatting and the older version .format() that was new in Python 2.6.
name = 'Python forum' count = 10 >>> print("{0:25} {1:3}".format(name, count), end=' ') Python forum 10 
With new f-string format new in Python 3.6,this is what you should use now.
>>> print(f"{name:25}{count:3}", end=' ') Python forum 10 
So eg it's padding and aligning of strings,can play around with <>^
>>> print(f"{name:>14}{count:^20}") Python forum 10 >>> print(f"{name:>20}{count:^5}") Python forum 10 >>> print(f"{name:>20}{count:<5}") Python forum10 >>> for word in 'f-strings are cool'.split(): ... print(f'{word.upper():~^20}') ... ~~~~~F-STRINGS~~~~~~ ~~~~~~~~ARE~~~~~~~~~ ~~~~~~~~COOL~~~~~~~~
Reply


User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020
This forum uses Lukasz Tkacz MyBB addons.
Forum use Krzysztof "Supryk" Supryczynski addons.