String Formatting¶
F-String diperkenalkan di Python 3.6, dan sekarang menjadi cara yang lebih disukai untuk memformat string.
Sebelum Python 3.6, kita harus menggunakan metode format().
F-Strings¶
F-string memungkinkan Anda memformat bagian-bagian tertentu dari sebuah string.
Untuk menetapkan sebuah string sebagai f-string, cukup letakkan huruf f di depan literal string, seperti ini:
#Create an f-string:
txt = f"The price is 49 dollars"
print(txt)
Placeholders and Modifiers¶
Untuk memformat nilai dalam f-string, tambahkan placeholder {}, placeholder dapat berisi variabel, operasi, fungsi, dan pengubah untuk memformat nilai.
#Add a placeholder for the price variable:
price = 59
txt = f"The price is {price} dollars"
print(txt) #result: The price is 59 dollars
Placeholder juga dapat menyertakan pengubah untuk memformat nilai.
Pengubah disertakan dengan menambahkan titik dua: diikuti oleh tipe format yang sah, seperti .2f yang berarti angka titik tetap dengan 2 desimal:
#Display the price with 2 decimals:
price = 59
txt = f"The price is {price:.2f} dollars"
print(txt) # The price is 59.00 dollars
Anda juga dapat memformat nilai secara langsung tanpa menyimpannya dalam variabel:
#Display the value 95 with 2 decimals:
txt = f"The price is {95:.2f} dollars"
print(txt)
Perform Operations in F-Strings¶
Anda dapat melakukan operasi Python di dalam placeholder.
Anda dapat melakukan operasi matematika:
txt = f"The price is {20 * 59} dollars"
print(txt) # The price is 1180 dollars
Anda dapat melakukan operasi matematika pada variabel:
#Add taxes before displaying the price:
price = 59 tax = 0.25 txt = f"The price is {price + (price * tax)} dollars" print(txt) # The price is 73.75 dollars
Anda dapat menjalankan pernyataan if...else di dalam placeholder:
#Return "Expensive" if the price is over 50, otherwise return "Cheap":
price = 49
txt = f"It is very {'Expensive' if price>50 else 'Cheap'}"
print(txt) # It is very Cheap
Execute Functions in F-Strings¶
Anda dapat menjalankan fungsi di dalam placeholder:
#Use the string method upper()to convert a value into upper case letters:
fruit = "apples"
txt = f"I love {fruit.upper()}"
print(txt) # I love APPLES
Fungsi tersebut tidak harus berupa metode Python bawaan, Anda dapat membuat fungsi Anda sendiri dan menggunakannya:
def myconverter(x):
return x * 0.3048
txt = f"The plane is flying at a {myconverter(30000)} meter altitude"
print(txt) # The plane is flying at a 9144.0 meter altitude
More Modifiers¶
Di awal bab ini, kami menjelaskan cara menggunakan pengubah .2f untuk memformat angka menjadi angka titik tetap dengan 2 desimal.
Ada beberapa pengubah lain yang dapat digunakan untuk memformat nilai:
#Use a comma as a thousand separator:
price = 59000
txt = f"The price is {price:,} dollars"
print(txt) # The price is 59,000 dollars
Berikut adalah daftar semua jenis pemformatan.
Formatting |
Types |
|---|---|
:< |
Left aligns the result (within the available space) |
:> |
Right aligns the result (within the available space) |
:^ |
Center aligns the result (within the available space) |
:= |
Places the sign to the left most position |
:+ |
Use a plus sign to indicate if the result is positive or negative |
:- |
Use a minus sign for negative values only |
: |
Use a space to insert an extra space before positive numbers (and a minus sign before negative numbers) |
:, |
Use a comma as a thousand separator |
:_ |
Use a underscore as a thousand separator |
:b |
Binary format |
:c |
Converts the value into the corresponding Unicode character |
:d |
Decimal format |
:e |
Scientific format, with a lower case e |
:E |
Scientific format, with an upper case E |
:f |
Fix point number format |
:F |
Fix point number format, in uppercase format (show inf and nan as INF and NAN) |
:g |
General format |
:G |
General format (using a upper case E for scientific notations) |
:o |
Octal format |
:x |
Hex format, lower case |
:X |
Hex format, upper case |
:n |
Number format |
:% |
Percentage format |
String format()¶
Sebelum Python 3.6, kami menggunakan metode format() untuk memformat string.
Metode format() masih dapat digunakan, tetapi f-string lebih cepat dan merupakan cara yang lebih disukai untuk memformat string.
Contoh berikutnya di halaman ini menunjukkan cara memformat string dengan metode format().
Metode format() juga menggunakan tanda kurung kurawal sebagai pengganti {}, tetapi sintaksnya sedikit berbeda:
#Add a placeholder where you want to display the price:
price = 49
txt = "The price is {} dollars"
print(txt.format(price))
Anda dapat menambahkan parameter di dalam tanda kurung kurawal untuk menentukan cara mengonversi nilai:
#Format the price to be displayed as a number with two decimals:
txt = "The price is {:.2f} dollars"
Multiple Values¶
Jika Anda ingin menggunakan lebih banyak nilai, cukup tambahkan lebih banyak nilai ke metode format():
print(txt.format(price, itemno, count))
Dan tambahkan lebih banyak tempat penampung:
quantity = 3
itemno = 567
price = 49
myorder = "I want {} pieces of item number {} for {:.2f} dollars."
print(myorder.format(quantity, itemno, price))
Index Numbers¶
Anda dapat menggunakan nomor indeks (angka di dalam tanda kurung kurawal {0}) untuk memastikan nilai ditempatkan di tempat penampung yang benar:
quantity = 3
itemno = 567
price = 49
myorder = "I want {0} pieces of item number {1} for {2:.2f} dollars."
print(myorder.format(quantity, itemno, price))
#result: I want 3 pieces of item number 567 for 49.00 dollars.
Selain itu, jika Anda ingin merujuk ke nilai yang sama lebih dari sekali, gunakan nomor indeks:
age = 36
name = "John"
txt = "His name is {1}. {1} is {0} years old."
print(txt.format(age, name))
#result: His name is John. John is 36 years old.
Named Indexes¶
Anda juga dapat menggunakan indeks bernama dengan memasukkan nama di dalam tanda kurung kurawal {carname}, tetapi kemudian Anda harus menggunakan nama saat meneruskan nilai parameter txt.format(carname = "Ford"):
myorder = "I have a {carname}, it is a {model}."
print(myorder.format(carname = "Ford", model = "Mustang"))
# I have a Ford, it is a Mustang.