Python Dizgi Biçimlendirme

To ensure that the string is displayed as expected, we can use format() method formats the result.

string format()

format() methods allow you to format selected parts of the string.

Sometimes part of the text is something you can't control, maybe they come from a database or user input?

To control such values, add placeholders (curly braces {}),then run the values through the format() method:

Örnek

Add a placeholder for the price to be displayed:

price = 52
txt = "The price is {} dollars"
print(txt.format(price))

Örneği Çalıştır

You can add parameters inside the curly braces to specify how to convert the values:

Örnek

Format the price as a number with two decimal places:

txt = "The price is {:.2f} dollars"

Örneği Çalıştır

See all format types in the string format() reference manual.

Multiple values

If you need more values, just add more values to the format() method:

print(txt.format(price, itemno, count))

and add more placeholders:

Örnek

quantity = 3
itemno = 567
price = 52
myorder = "I want {} pieces of item number {} for {:.2f} dollars."
print(myorder.format(quantity, itemno, price))

Örneği Çalıştır

İndeks numarası

İndeks numarasını (parantez içinde) kullanarak indeks numarasını gösterebilirsiniz: {0} Düzenleyerek doğru yerleştirme sağlamak için sayıları kullanarak (parantez içinde) değerleri doğru yerleştirin:

Örnek

quantity = 3
itemno = 567
price = 52
myorder = "I want {0} pieces of item number {1} for {2:.2f} dollars."
print(myorder.format(quantity, itemno, price))

Örneği Çalıştır

Ayrıca, aynı değeri birden fazla kez kullanmak istiyorsanız, indeks numarasını kullanın:

Örnek

age = 63
name = "Bill"
txt = "His name is {1}. {1} is {0} years old."
print(txt.format(age, name))

Örneği Çalıştır

Adlandırılmış indeks

Ayrıca, parantez içindeki sayıları kullanarak değerleri doğru yerleştirmek için: {carname} Adlandırılmış indeks kullanmak için isim girin, ancak parametre değerlerini txt.format(carname = "Ford") ile iletirken isim kullanmanız gerekir:

Örnek

myorder = "I have a {carname}, it is a {model}."
print(myorder.format(carname = "Porsche", model = "911"))

Örneği Çalıştır