字符串格式化#

介绍#

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().

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)))

Formatting Numbers with .format – Insert values and expressions into a string.

  • :.xf – 设置要显示的小数位数。

  • round – 将数字四舍五入到指定的小数位数。

  • :, – 添加逗号作为千位分隔符。

  • :.x% – 将小数转换为保留 x 位小数的百分比。

  • :#x – 将数字格式化为十六进制。

  • :b – 将数字格式化为二进制。

合并字符串 – 将文本和值合并在一起。

  • .format – 在单个表达式中合并字符串和变量。

  • +运算符 – 手动连接字符串,并可选择进行类型转换。

字符串方法 – 更改文本的大小写。

  • upper – 将所有字符转换为大写。

  • lower – 将所有字符转换为小写。

检查子字符串 – 测试文本是否存在或位置。

  • in – 检查字符串中是否存在某个单词。

  • startswith – 检查字符串是否以给定值开头。

  • endswith – 检查字符串是否以给定值结尾。

转义序列 – 使用特殊字符格式化输出。

  • \n – 添加换行符(新行)。

  • \t – 在项目之间添加制表符空格。

Formatting Numbers with .format#

.format can be used to control how numbers appear, including decimal places, rounding, and other formatting styles such as:

Fixed Decimal Places#

.xf controls how many decimal places a number is displayed with.

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 rounds a number to a specific number of decimal places before formatting.

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#

:, inserts commas as thousands separators to make large numbers more readable.

Usage:
:,

参数

描述

此格式说明符没有参数。

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

Percentage#

:.x% formats decimal values as percentages.

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 converts numbers to hexadecimal.

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 converts numbers to binary (base 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#

Insert values directly into the string using {}.

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#

Join multiple parts by using +.

Note: Non-strings must first be converted to strings using 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 converts all letters in a string to uppercase.

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 converts all letters in a string to lowercase.

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 is a keyword that returns a Boolean indicating whether a word exists in a string.

  • True - The word exists in the string.

  • False - The word does not exist in the string.

def main():
    message = "Hey everyone!"
    if "Hey" in message:
        console.print("Hello!")

# Start threads — Do not delete
start_thread(main)

startswith#

startswith returns a Boolean indicating whether a string begins with a given value.

  • True - The word starts the string.

  • False - The word does not start the string.

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 returns a Boolean indicating whether a string ends with a given value.

  • True - The word ends the string.

  • False - The word does not end the string.

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 moves text to a new line when printing.

def main():
    # Display text on two lines
    console.print("First line\nSecond line")

# Start threads — Do not delete
start_thread(main)

Tab Spacing#

\t inserts a tab space between words or numbers.

def main():
    # Display the quantity of disks
    quantity = 2
    console.print("Disks:\t", quantity)

# Start threads — Do not delete
start_thread(main)