字串格式化#

介紹#

在 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-strings – 將變數和表達式直接嵌入文字中。

  • f”{value}” – 顯示字串中的變數、表達式或函數呼叫。

格式化 f 字串中的數字 - 控制數值的顯示方式。

  • :.xf – 設定要顯示的小數位數。

  • round – 將數字四捨五入到指定的小數位數。

  • :, – 新增逗號作為千位分隔符號。

  • :.x% – 將小數轉換為保留 x 位小數的百分比。

  • :#x – 將數字格式化為十六進位。

  • :b – 將數字格式化為二進位。

字串組合-組合文字和值。

  • f”{value}” – 在單一表達式中組合字串和變數。

  • + 運算子 – 手動連接字串,並可選擇進行類型轉換。

字串方法-更改文字的大小寫。

  • upper – 將所有字元轉換為大寫。

  • lower – 將所有字元轉換為小寫。

子字串檢查-測試文字的存在或位置。

  • in – 檢查字串中是否存在某個單字。

  • startswith – 檢查字串是否以給定值開頭。

  • endswith – 檢查字串是否以給定值結尾。

轉義序列-使用特殊字元格式化輸出。

  • \n – 新增換行符號(新行)。

  • \t – 在項目之間加入製表符空格。

在 f 字串中格式化數字#

f 字串允許使用以下格式說明符精確控制小數位、舍入、千位分隔符號等:

Fixed Decimal Places#

.xf 控制數字顯示的小數位數。

用法:
.xf

參數

描述

x

要顯示的小數位數。

# Display pi with 2 decimal places
pi = 3.1415926535
controller.screen.print(f"Pi: {pi:.2f}")

# Output: Pi: 3.14

Rounding Numbers#

round 將 f 字串之外或 {}內的數字輪轉。

用法:
round(number, x)

參數

描述

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#

, 使大數字更易讀。

用法:
,

參數

描述

此格式說明符沒有參數。

# Display a large number separated with commas
number = 1234567
controller.screen.print(f"{number:,}")

# Output: 1,234,567

Percentage#

.x% 將十進位值格式化為百分比。

用法:
.x%

參數

描述

x

要顯示的小數位數。

# Display a converted decimal to a percentage
value = 0.875

controller.screen.print(f"{value:.1%}")

# Output: 87.5%

Hexadecimal#

.#x 將數字轉換為十六進位。

用法:
.#x

參數

描述

此格式說明符沒有參數。

# Convert 255 to hexadecimal
number = 255

controller.screen.print(f"{number:#x}")

# Output: 0xff

Binary#

b 將數字轉換為二進位(以 2 為基數)。

用法:
b

參數

描述

此格式說明符沒有參數。

# Convert 3 to binary
controller.screen.print(f"Binary: {3:b}")

# Output: Binary: 11

組合字串#

您可以使用兩種方法來組合(或連接)字串:

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 將字串中的所有字母轉換為大寫。

用法:
upper()

參數

描述

此方法沒有參數。

# Display a message in uppercase
message = "vexcode"

controller.screen.print(message.upper())

# Output: VEXCODE

lower#

lower 將字串中的所有字母轉換為小寫。

用法:
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 – 該單字不是字串的開頭。

用法:
startswith(substring)

參數

描述

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 – 該單字未結束字串。

用法:
endswith(substring)

參數

描述

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)