文字列の書式設定#
導入#
Python でテキストや数値をフォーマットする推奨方法は f 文字列を使用することです。これにより、変数、式、関数呼び出しを {}の中に直接埋め込むことができます。
f文字列を作成するには、文字列の前に f を追加し、変数、式、または関数呼び出しを {}の中に配置します。
x = 1
y = 5
# Display the variables using an f-string
controller.screen.print(f"Position: ({x}, {y})")
# Display a calculation with an f-string
controller.screen.print(f"Sum: {5 + 3}")
# Display the robot's battery capacity with an f-string
controller.screen.print(f"Battery: {controller.get_battery_level()}%")
f文字列 – 変数と式をテキストに直接埋め込む。
f”{value}”– 文字列内の変数、式、または関数呼び出しを表示します。
f文字列における数値の書式設定 – 数値の表示方法を制御する。
:.xf– 表示する小数点以下の桁数を設定します。round– 数値を指定された小数点以下の桁数に丸めます。:,– カンマを千の位の区切り文字として追加します。:.x%– 小数を x 桁の小数点以下のパーセントに変換します。:#x– 数値を16進数としてフォーマットします。:b– 数値をバイナリ形式にします。
文字列結合 – テキストと値を結合します。
f”{value}”– 文字列と変数を単一の式に組み合わせます。+演算子 – オプションの型変換を使用して文字列を手動で連結します。
文字列メソッド – テキストの大文字/小文字を変更する。
部分文字列チェック – テキストの存在または位置をテストします。
in– 文字列内に単語が存在するかどうかを確認します。startswith– 文字列が指定された値で始まるかどうかをチェックします。endswith– 文字列が指定された値で終わるかどうかを確認します。
エスケープシーケンス – 特殊文字を使用して出力をフォーマットします。
f文字列における数値の書式設定#
f文字列では、以下の書式指定子を使用することで、小数点以下の桁数、丸め処理、桁区切り記号などを正確に制御できます。
Fixed Decimal Places#
.xf 、数値の小数点以下の桁数を制御します。
Usage:
.xf
パラメータ |
説明 |
|---|---|
|
表示する小数点以下の桁数。 |
# Display pi with 2 decimal places
pi = 3.1415926535
controller.screen.print(f"Pi: {pi:.2f}")
# Output: Pi: 3.14
Rounding Numbers#
round rounds numbers outside of an f-string or inside of the {}.
Usage:
round(number, x)
パラメータ |
説明 |
|---|---|
|
四捨五入する数値。 |
|
丸める小数点以下の桁数。 |
# Display a value rounded to only 2 decimal places
value = 5.6789
controller.screen.print(f"{round(value, 2)}")
# Output: 5.68
Thousands Separator#
, 、大きな数字を読みやすくするために、桁区切りとしてカンマを挿入します。
Usage:
,
パラメータ |
説明 |
|---|---|
この書式指定子にはパラメータがありません。 |
# Display a large number separated with commas
number = 1234567
controller.screen.print(f"{number:,}")
# Output: 1,234,567
Percentage#
.x% は、小数値をパーセンテージとしてフォーマットします。
Usage:
.x%
パラメータ |
説明 |
|---|---|
|
表示する小数点以下の桁数。 |
# Display a converted decimal to a percentage
value = 0.875
controller.screen.print(f"{value:.1%}")
# Output: 87.5%
Hexadecimal#
.#x は数値を 16 進数に変換します。
Usage:
.#x
パラメータ |
説明 |
|---|---|
この書式指定子にはパラメータがありません。 |
# Convert 255 to hexadecimal
number = 255
controller.screen.print(f"{number:#x}")
# Output: 0xff
Binary#
b は数値をバイナリ (基数 2) に変換します。
Usage:
b
パラメータ |
説明 |
|---|---|
この書式指定子にはパラメータがありません。 |
# Convert 3 to binary
controller.screen.print(f"Binary: {3:b}")
# Output: Binary: 11
文字列の結合#
文字列を結合(連結)するには、次の2つの方法があります。
Using f-strings#
f文字列では、変数を {}の中に直接埋め込むことができます。
# Display an answer based on the given emotion
emotion = "good"
controller.screen.print(f"I'm {emotion}, you?")
+ Operator#
+ 演算子を使用して、文字列を手動で結合できます。
注: 文字列以外のものは、まず str()を使用して文字列に変換する必要があります。
# Display the x and y values
x = 10
y = 20
controller.screen.print("X: " + str(x) + ", Y: " + str(y))
文字列メソッド#
Pythonには、文字列の変更やチェックを行うための組み込みメソッドが用意されています。
upper#
upper 、文字列内のすべての文字を大文字に変換します。
Usage:
upper()
パラメータ |
説明 |
|---|---|
このメソッドにはパラメータがありません。 |
# Display a message in uppercase
message = "vexcode"
controller.screen.print(message.upper())
# Output: VEXCODE
lower#
lower 、文字列内のすべての文字を小文字に変換します。
Usage:
lower()
パラメータ |
説明 |
|---|---|
このメソッドにはパラメータがありません。 |
# Display a message in lowercase
message = "VEXCODE"
controller.screen.print(message.lower())
# Output: vexcode
部分文字列のチェック#
in#
in は、文字列内に部分文字列(単語またはテキストの一部)が存在するかどうかを示すブール値を返すキーワードです。
True– その単語は文字列内に存在します。False– 文字列内にその単語が存在しません。
# Display a message if "Hey" is in the string
message = "Hey everyone!"
if "Hey" in message:
controller.screen.print("Hello!")
startswith#
startswith は、文字列が指定された値で始まるかどうかを示すブール値を返します。
True– その単語が文字列の開始位置になります。False– その単語は文字列の先頭にありません。
Usage:
startswith(substring)
パラメータ |
説明 |
|---|---|
|
文字列の先頭でチェックする部分文字列。 |
# Display a message if the string starts with "AIR"
message = "AIR Drone"
if message.startswith("AIR"):
controller.screen.print("AIR first!")
endswith#
endswith は、文字列が指定された値で終わるかどうかを示すブール値を返します。
True– その単語は文字列の終わりです。False– その単語は文字列の終わりではありません。
Usage:
endswith(substring)
パラメータ |
説明 |
|---|---|
|
文字列の末尾でチェックする部分文字列。 |
# Display a message if the string ends with "Drone"
message = "AIR Drone"
if message.endswith("Drone"):
controller.screen.print("Drone last!")
脱出シーン#
エスケープシーケンスは、文字列内でテキスト出力の書式設定に使用される特殊文字です。これらは コンソール でのみ使用できます。
New Line#
\n 、印刷時にテキストを新しい行に移動します。
# Display text on two lines
print("First line\nSecond line")
Tab Spacing#
\t は、単語または数字の間にタブスペースを挿入します。
# Display the quantity of barrels
quantity = 2
print("IDs:\t", quantity)