字串格式化#

介紹#

f-string 是 Python 中格式化文字和數字的建議方法。它們允許將變數、表達式和函數呼叫直接嵌入到 {}中。

若要建立 f 字串,請在字串前新增 f ,並將任何變數、表達式或函數呼叫放在 {}內。

x = 1
y = 5

# Display the variables using an f-string
robot.screen.print(f"Position: ({x}, {y})")

# Display a calculation with an f-string
robot.screen.print(f"Sum: {5 + 3}")

# Display the robot's battery capacity with an f-string
robot.screen.print(f"Battery: {robot.get_battery_level()}%")

f-Strings – 直接在文字中嵌入變數和表達式。

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

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

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

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

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

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

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

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

字串組合 – 將文字和值組合在一起。

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

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

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

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

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

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

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

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

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

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

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

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

在 f 字串中格式化數字#

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

Fixed Decimal Places#

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

用法:
.xf

參數

描述

x

顯示的小數位數。

# Display pi with 2 decimal places
pi = 3.1415926535
robot.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
robot.screen.print(f"{round(value, 2)}")  # Output: 5.68

Thousands Separator#

, 使大數字更易讀。

用法:
,

參數

描述

此格式說明符沒有參數。

# Display a large number separated with commas
number = 1234567
robot.screen.print(f"{number:,}")  # Output: 1,234,567

Percentage#

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

用法:
.x%

參數

描述

x

顯示的小數位數。

# Display a converted decimal to a percentage
value = 0.875
robot.screen.print(f"{value:.1%}")  # Output: 87.5%

Hexadecimal#

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

用法:
.#x

參數

描述

此格式說明符沒有參數。

# Convert 255 to hexadecimal
number = 255
robot.screen.print(f"{number:#x}")  # Output: 0xff

Binary#

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

用法:
b

參數

描述

此格式說明符沒有參數。

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

字串合併#

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

Using f-strings#

使用 f 字串,您可以將變數直接嵌入到 {}中。

# Display an answer based on the given emotion
emotion = "good"
robot.screen.print(f"I'm {emotion}, you?")

+ Operator#

您可以使用 + 運算子手動組合字串。

注意:非字串必須先使用 str()

# Display the x and y values
x = 10
y = 20
robot.screen.print("X: " + str(x) + ", Y: " + str(y))

字串方法#

Python 提供了用於修改和檢查字串的內建方法。

upper#

upper 將字串中的所有字母轉換為大寫。

用法:
upper()

參數

描述

此方法沒有參數。

message = "vexcode"
robot.screen.print(message.upper())  # Output: VEXCODE

lower#

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

用法:
lower()

參數

描述

此方法沒有參數。

message = "VEXCODE"
robot.screen.print(message.lower())  # Output: vexcode

檢查子字串#

in#

in 是一個關鍵字,它傳回一個布林值,指示子字串(單字或文字片段)是否存在於字串中。

  • True – 該單字存在於字串中。

  • False – 該單字不存在於字串中。

message = "Hey everyone!"
if "Hey" in message:
    robot.screen.print("Hello!")

startswith#

startswith 傳回一個布林值,指示字串是否以給定值開頭。

  • True – 該單字位於字串的開頭。

  • False – 該單字不是字串的開頭。

用法:
startswith(substring)

參數

描述

substring

要檢查的子字串是否位於字串的開頭。

message = "AIM Robot"

if message.startswith("AIM"):
    robot.screen.print("AIM first!")

endswith#

endswith 傳回布林值,指示字串是否以給定值結尾。

  • True – 該單字結束字串。

  • False – 該單字未結束字串。

用法:
endswith(substring)

參數

描述

substring

要檢查的字串末尾的子字串。

message = "AIM Robot"

if message.endswith("Robot"):
    robot.screen.print("Robot 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("Barrels:\t", quantity)