字串格式化#

介紹#

Python 中的 .format() 方法用於建立包含變數、表達式或值的字串。此方法會將字串中的花括號佔位 .format() 替換為 {}內部提供的值。

x = 1
y = 5

# Display the variables using .format()
print("Position: ({}, {})".format(x, y))

# Display a calculation using .format()
print("Sum: {}".format(5 + 3))

wait(1, SECONDS)
# Display the time using .format()
print("Time: {}".format(timer.time(SECONDS)))

使用 .format 格式化數字 – 將值和表達式插入字串。

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

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

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

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

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

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

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

  • .format() – 在單一表達式中組合字串和變數。

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

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

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

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

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

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

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

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

轉義序列 – 用於格式化包含特殊字元的輸出。

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

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

使用 .format#

.format 可用來控制數字的顯示方式,包括小數位數、四捨五入以及其他格式樣式,例如:

Fixed Decimal Places#

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

Usage:
:.xf

參數

描述

x

顯示的小數位數。

# Display pi with 2 decimal places
pi = 3.1415926535
console.print("Pi: {:.2f}".format(pi))
# Output: Pi: 3.14

Rounding Numbers#

round 在格式化之前將數字四捨五入到指定的小數位數。

Usage:
round(number, x)

參數

描述

number

要四捨五入的數字。

x

四捨五入到小數點後的位數。

# Display a value rounded to only 2 decimal places
value = 5.6789
console.print("Rounded: {}".format(round(value, 2)))
# Output: Rounded: 5.68

Thousands Separator#

:, 插入逗號作為千位分隔符,使大數字更易讀。

Usage:
:,

參數

描述

此格式說明符沒有參數。

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

Percentage#

:.x% 將十進制值乘以 100 並添加百分號,從而將十進位值格式化為百分比。

Usage:
:.x%

參數

描述

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 將數字轉換為十六進位。

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)

字串合併#

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

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)

參數

描述

substring

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

def main():
    # Check for 'V5' at the start of a string
    message = "V5 Robot"

    if message.startswith("V5"):
        console.print("V5 first!")

# Start threads — Do not delete
start_thread(main)

endswith#

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

  • True – 該單字結束字串。

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

Usage:
endswith(substring)

參數

描述

substring

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

def main():
    # Check for `Robot` at the end of a string
    message = "V5 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)