文字列の書式設定#
導入#
The .format() method in Python is used to create strings that include variables, expressions, or values. This method replaces curly brace placeholders {} in a string with values provided inside .format().
def main():
x = 1
y = 5
# Display the variables using .format()
console.print("Position: ({}, {})".format(x, y))
# Start threads — Do not delete
start_thread(main)
def main():
# Display a calculation using .format()
console.print("Sum: {}".format(5 + 3))
# Start threads — Do not delete
start_thread(main)
def main():
wait(1, SECONDS)
# Display the time using .format()
console.print("Time: {}".format(timer.time(SECONDS)))
# Start threads — Do not delete
start_thread(main)
数値の書式設定( .format – 文字列に値と式を挿入します。
:.xf– 表示する小数点以下の桁数を設定します。round– 数値を指定された小数点以下の桁数に丸めます。:,– カンマを千の位の区切り文字として追加します。:.x%– 小数を x 桁の小数点以下のパーセントに変換します。:#x– 数値を16進数としてフォーマットします。:b– 数値をバイナリ形式にします。
文字列の結合 – テキストと値を結合します。
.format()– 文字列と変数を単一の式に組み合わせます。+ operator– オプションの型変換を使用して文字列を手動で連結します。
文字列メソッド – テキストの大文字/小文字を変更する。
部分文字列のチェック – テキストの存在または位置をテストします。
in– 文字列内に単語が存在するかどうかを確認します。startswith()– 文字列が指定された値で始まるかどうかを確認します。endswith()– 文字列が指定された値で終わるかどうかを確認します。
エスケープシーケンス – 特殊文字を使用して出力をフォーマットします。
数値を .format#
.format 使用すると、小数点以下の桁数、丸め処理、その他の書式設定スタイルなど、数値の表示方法を制御できます。
Fixed Decimal Places#
:.xf 、数値の小数点以下の桁数を制御します。
Usage:
:.xf
パラメータ |
説明 |
|---|---|
|
表示する小数点以下の桁数。 |
def main():
# Display pi with 2 decimal places
pi = 3.1415926535
console.print("Pi: {:.2f}".format(pi))
# Output: Pi: 3.14
# Start threads — Do not delete
start_thread(main)
Rounding Numbers#
round は、書式設定を行う前に数値を特定の小数点以下の桁数に丸めます。
Usage:
round(number, x)
パラメータ |
説明 |
|---|---|
|
四捨五入する数値。 |
|
丸める小数点以下の桁数。 |
def main():
# Display a value rounded to only 2 decimal places
value = 5.6789
console.print("Rounded: {}".format(round(value, 2)))
# Output: Rounded: 5.68
# Start threads — Do not delete
start_thread(main)
Thousands Separator#
:, 、大きな数字を読みやすくするために、桁区切りとしてカンマを挿入します。
Usage:
:,
パラメータ |
説明 |
|---|---|
この書式指定子にはパラメータがありません。 |
def main():
# Display a large number separated with commas
number = 1234567
console.print("Formatted: ")
console.new_line()
console.print("{:,}".format(number))
# Output: Formatted: 1,234,567
# Start threads — Do not delete
start_thread(main)
Percentage#
:.x% は、小数値を 100 倍してパーセント記号を追加することにより、パーセント形式に変換します。
Usage:
:.x%
パラメータ |
説明 |
|---|---|
|
表示する小数点以下の桁数。 |
def main():
# Display a converted decimal to a percentage
value = 0.875
console.print("Score: {:.1%}".format(value))
# Output: Score: 87.5%
# Start threads — Do not delete
start_thread(main)
Hexadecimal#
:#x は数値を 16 進数に変換します。
Usage:
:#x
パラメータ |
説明 |
|---|---|
この書式指定子にはパラメータがありません。 |
def main():
# Convert 255 to hexadecimal
number = 255
console.print("Hex: {:#x}".format(number))
# Output: Hex: 0xff
# Start threads — Do not delete
start_thread(main)
Binary#
:b 数値をバイナリ (基数 2) に変換します。
Usage:
:b
パラメータ |
説明 |
|---|---|
この書式指定子にはパラメータがありません。 |
def main():
# Convert 3 to binary
console.print("Binary: {:b}".format(3))
# Output: Binary: 11
# Start threads — Do not delete
start_thread(main)
文字列の結合#
文字列を結合(連結)するには、次の2つの方法があります。
Using .format#
{}を使用して文字列に直接値を挿入します。
def main():
# Display an answer based on the given emotion
emotion = "good"
console.print("I'm {}, you?".format(emotion))
# Start threads — Do not delete
start_thread(main)
+ Operator#
+を使用して複数のパーツを結合します。
注: 文字列以外のものは、まず str()を使用して文字列に変換する必要があります。
def main():
# Display the x and y values
x = 10
y = 20
console.print("X: " + str(x) + ", Y: " + str(y))
# Start threads — Do not delete
start_thread(main)
文字列メソッド#
Pythonには、文字列の変更やチェックを行うための組み込みメソッドが用意されています。
upper#
upper 、文字列内のすべての文字を大文字に変換します。
Usage:
upper()
パラメータ |
説明 |
|---|---|
このメソッドにはパラメータがありません。 |
def main():
# Capitalize a string with .upper()
message = "vexcode"
console.print(message.upper()) # Output: VEXCODE
# Start threads — Do not delete
start_thread(main)
lower#
lower 、文字列内のすべての文字を小文字に変換します。
Usage:
lower()
パラメータ |
説明 |
|---|---|
このメソッドにはパラメータがありません。 |
def main():
# Make a string lowercase with .lower()
message = "VEXCODE"
console.print(message.lower()) # Output: vexcode
# Start threads — Do not delete
start_thread(main)
部分文字列のチェック#
in#
in は、文字列内に部分文字列(単語またはテキストの一部)が存在するかどうかを示すブール値を返すキーワードです。
True– その単語は文字列内に存在します。False– 文字列内にその単語が存在しません。
def main():
message = "Hey everyone!"
if "Hey" in message:
console.print("Hello!")
# Start threads — Do not delete
start_thread(main)
startswith#
startswith は、文字列が指定された値で始まるかどうかを示すブール値を返します。
True– その単語が文字列の開始位置になります。False– その単語は文字列の先頭にありません。
Usage:
startswith(substring)
パラメータ |
説明 |
|---|---|
|
文字列の先頭でチェックする部分文字列。 |
def main():
# Check for 'GO' at the start of a string
message = "GO Robot"
if message.startswith("GO"):
console.print("GO first!")
# Start threads — Do not delete
start_thread(main)
endswith#
endswith は、文字列が指定された値で終わるかどうかを示すブール値を返します。
True– その単語は文字列の終わりです。False– その単語は文字列の終わりではありません。
Usage:
endswith(substring)
パラメータ |
説明 |
|---|---|
|
文字列の末尾でチェックする部分文字列。 |
def main():
# Check for `Robot` at the end of a string
message = "GO Robot"
if message.endswith("Robot"):
console.print("Robot last!")
# Start threads — Do not delete
start_thread(main)
脱出シーン#
エスケープシーケンスとは、文字列内でテキスト出力の書式を整えるために使用される特殊文字のことです。
New Line#
\n 、印刷時にテキストを新しい行に移動します。
def main():
# Display text on two lines
console.print("First line\nSecond line")
# Start threads — Do not delete
start_thread(main)
Tab Spacing#
\t は、単語または数字の間にタブスペースを挿入します。
def main():
# Display the quantity of disks
quantity = 2
console.print("Disks:\t", quantity)
# Start threads — Do not delete
start_thread(main)