字符串格式化#

介绍#

f 字符串是 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}” – Displays variables, expressions, or function calls inside a string.

在 f 字符串中格式化数字 - 控制数值的显示方式。

  • :.xf – Sets the number of decimal places to show.

  • round – Rounds a number to a given number of decimal places.

  • :, – Adds commas as thousands separators.

  • :.x% – Converts a decimal to a percentage with x decimal places.

  • :#x – Formats a number as hexadecimal.

  • :b – Formats a number as binary.

字符串组合——组合文本和值。

  • f”{value}” – Combine strings and variables in a single expression.

  • + operator – Concatenate strings manually with optional type conversion.

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

  • upper() – Converts all characters to uppercase.

  • lower() – Converts all characters to lowercase.

子字符串检查——测试文本的存在或位置。

  • in – Checks if a word exists in a string.

  • startswith() – Checks if a string begins with a given value.

  • endswith() – Checks if a string ends with a given value.

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

  • \n – Adds a line break (new line).

  • \t – Adds a tab space between items.

在 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 - 该词不会结束字符串。

用法:
startswith(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)