Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Advanced Formatting Options | Formatting and Type Conversion
Strings and Data Formats in Python

bookAdvanced Formatting Options

メニューを表示するにはスワイプしてください

When you need to control exactly how numbers and text appear in your output, advanced formatting options in Python's f-strings give you powerful tools. You can specify decimal precision for floating-point numbers, control the width of fields, and align text for clear, readable tables. These features are especially useful when you want your data to look professional and well-organized, such as when displaying financial figures or tabular data.

12345678910111213141516
# Formatting floating-point numbers to two decimal places price = 12.3456 formatted_price = f"{price:.2f}" print(f"Price: {formatted_price}") # Aligning text in columns using width specifiers and alignment header1 = "Product" header2 = "Price" row1 = "Apple" row2 = "Banana" price1 = 1.25 price2 = 0.75 print(f"{header1:<10} | {header2:>7}") print(f"{row1:<10} | {price1:>7.2f}") print(f"{row2:<10} | {price2:>7.2f}")
copy

You can also format integers with leading zeros by using the 0 character in your width specifier. This is helpful for things like invoice numbers, timestamps, or any case where you want a number to always appear with a fixed number of digits. The width specifier controls the minimum number of characters for the field, padding with spaces or zeros as needed. For example, f"{5:03}" will display 005. Alignment specifiers like <, >, and ^ can be used to left-align, right-align, or center text within a given width, making your output easy to read.

1. How do you format a float to display two decimal places using an f-string?

2. Which format specifiers can be used for text alignment in f-strings?

question mark

How do you format a float to display two decimal places using an f-string?

正しい答えを選んでください

question mark

Which format specifiers can be used for text alignment in f-strings?

すべての正しい答えを選択

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 2.  3

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 2.  3
some-alt