0

what is meaning of this line [print("{0} - {1}%".format(char, round(perc, 2)))] in below code?

def count_char(text, char): count = 0 for c in text: if c == char: count += 1 return count file = open("newfile.txt", "w") file.write("""Ornhgvshy vf orggre guna htyl. Rkcyvpvg vf orggre guna vzcyvpvg. Fvzcyr vf orggre guna pbzcyvpngrq. Syng vf orggre guna arfgrq. Fcenfr fv orggre guna qrafr. Ernqnovyvgl pbhagf. Fcrpvny pnfrf nera'g fcrpvny rabthu gb oernx gur ehyrf. Nygubhtu cenpgvpnyvgl orgnf chevgl. Reebef fubhyq arire cnff fvyragyl. Hayrff rkcyvpvgyl fvyraprq. Va gur snpr bs nzovthvgl, ershfr gur grzcgngvba bg thrff. Gurer fubhyq or bar-- naq cersrenoylbayl bar --boivbhf jnl gb qb vg. Nygubhtu gung jnl znl abg or boivbhf ng svefg hayrff lbh'er Qhgpu. Abj vf orggre guna arrire. Nygubhtu arire vf bsgra orggre guna *evtug* abj. Vs gur vzcyrzragngvba vf uneq gb rkcynva, vg'f n onq vqrn. Vs gur vzcyrzragngvba vf rnfl gb rkcynva, vg znl or n tbbq vqrn. Anzrfcnprf ner bar ubaxvat terng vqrn -- yrg'f qb zber bs gubfr!""") file.close() filename = "newfile.txt" with open(filename) as f: text = f.read() for char in "abcdefghijklmnopqrstuvwxyz": perc = 100 * count_char(text, char) / len(text) print("{0} - {1}%".format(char, round(perc, 2)))

23rd Mar 2019, 5:52 PM
Dee Pan Kar
Dee Pan Kar - avatar
2 Réponses
+ 4
hi Dee, the print function is making an output to screen in defined and formatted way. You can see there two placeholders with curly brackets and numbers '0' and '1' inside. These are consecutive numbers and they corresponde with the 'data source' inside the .format(...). So the content of the char variable will be at the placeholder {0} and the perc variable in the {1} placeholder. perc variable is additionally rounded with round() for 2 decimals. The lack is that the result does not show 2 decimals at all positions in the output. But this can be fixed with a small change in code (see example) Code: prin{t("{0} - {1}%".format(char, round(perc, 2))) # adding more format options: print("{0} - {1:.2f}%".format(char, round(perc, 2))) Output original: a - 4.68% b - 4.94% c - 2.28% d - 0.0% e - 3.8% Output modified: a - 4.68% b - 4.94% c - 2.28% d - 0.00% e - 3.80% Hope that helps!
23rd Mar 2019, 7:08 PM
Lothar
Lothar - avatar
0
thanks lothar
24th Mar 2019, 9:48 AM
Dee Pan Kar
Dee Pan Kar - avatar