4-mavzu: shart operatorlari va sikllar


Butun sonlarni formatlash


Download 42.54 Kb.
bet19/20
Sana14.03.2023
Hajmi42.54 Kb.
#1266970
1   ...   12   13   14   15   16   17   18   19   20
Bog'liq
Python. 2-maruza

Butun sonlarni formatlash:

1
2
3
4

source = "{:d} belgi"
number = 5
target = source.format(number)
print(target) # 5 belgi

Agar formatlash kerak bo'lgan raqam 999 dan katta bo'lsa, to'ldiruvchi ta'rifida minglik ajratuvchi sifatida verguldan foydalanishni belgilashimiz mumkin:

1
2

source = "{:,d} belgi"
print(source.format(5000)) # 5,000 belgi

Bundan tashqari, placeholderlar f-satrlarida ham ishlatilishi mumkin:

1
2
3

n = 5000
source = f"{n:,d} belgi"
print(source) # 5,000 belgi

Kasr sonlari, ya'ni float turini ifodalovchilar uchun, nuqtadan keyin placeholder koddan oldin, kasr qismida qancha belgi ko'rsatishni xohlashimizni belgilashingiz mumkin:

1
2
3
4
5

number = 23.8589578
print("{:.2f}".format(number)) # 23.86
print("{:.3f}".format(number)) # 23.859
print("{:.4f}".format(number)) # 23.8590
print("{:,.2f}".format(10001.23554)) # 10,001.24

Yana bir parametr formatlangan qiymatning minimal kengligini belgilar bilan belgilash imkonini beradi:

1
2

print("{:10.2f}".format(23.8589578)) # 23.86
print("{:8d}".format(25)) # 25

f-satrlari bilan o'xshash misol:

1
2
3
4

n1 = 23.8589578
print(f"{n1:10.2f}") # 23.86
n2 = 25
print(f"{n2:8d}") # 25

Foizlarni chiqarish uchun "%" kodini ishlatish yaxshiroqdir:

1
2
3
4
5
6
7
8

number = .12345
print("{:%}".format(number)) # 12.345000%
print("{:.0%}".format(number)) # 12%
print("{:.1%}".format(number)) # 12.3%
print(f"{number:%}") # 12.345000%
print(f"{number:.0%}") # 12%
print(f"{number:.1%}") # 12.3%

Raqamni eksponensial belgilarda ko'rsatish uchun "e" placeholder ishlatiladi:

1
2
3
4
5
6
7
8

number = 12345.6789
print("{:e}".format(number)) # 1.234568e+04
print("{:.0e}".format(number)) # 1e+04
print("{:.1e}".format(number)) # 1.2e+04
print(f"{number:e}") # 1.234568e+04
print(f"{number:.0e}") # 1e+04
print(f"{number:.1e}") # 1.2e+04


Download 42.54 Kb.

Do'stlaringiz bilan baham:
1   ...   12   13   14   15   16   17   18   19   20




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling