字符串格式#

简介#

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 – Embed variables and expressions directly in text.

  • [f”{value}”] (#introduction) –显示字符串内的变量、表达式或函数调用。

Formatting Numbers in f-strings – Control how numeric values appear.

  • [:.xf] (#fixed-decimal-places) –设置要显示的小数位数。

  • [round] (#rounding-numbers) –将数字舍入到给定的小数位数。

  • [:,] (#thousands-separator) –将逗号添加为千位分隔符。

  • [:.x%] (#percentage) –将小数转换为包含x位小数的百分比。

  • [:#x] (#hexadecimal) –将数字格式化为十六进制。

  • [:b] (#binary) –将数字格式化为二进制。

String Combination – Combine text and values.

  • [f”{value}”] (#using-f-strings) –在单个表达式中组合字符串和变量。

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

String Methods – Change the case of text.

  • upper() – Converts all characters to uppercase.

  • lower() – Converts all characters to lowercase.

Substring Checks ––Test for presence or position of text.

  • 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.

Escape Sequences – Format output with special characters.

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

  • \t – Adds a tab space between items.

格式化f字符串中的数字#

f 字符串允许使用以下格式说明符精确控制小数位、舍入、千位分隔符等:

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
robot.screen.print(f"Pi: {pi:.2f}")  # Output: Pi: 3.14

Rounding Numbers#

round 舍入f字符串外部或 {}内部的数字。

Usage:
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#

, 插入逗号作为千位分隔符,使大数字更易于阅读。

Usage:
,

参数

描述

此格式说明符没有参数。

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

Percentage#

.x% 格式将十进制值设置为百分比。

Usage:
.x%

参数

描述

x

要显示的小数位数。

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

Hexadecimal#

.#x 将数字转换为十六进制。

Usage:
.#x

参数

描述

此格式说明符没有参数。

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

Binary#

b 将数字转换为二进制(以2为底)。

Usage:
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#

您可以使用 + 运算符手动组合字符串。

Note: Non-strings must first be converted to strings using str().

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

字符串方法#

Python 提供了修改和检查字符串的内置方法。

upper#

upper 将字符串中的所有字母转换为大写。

Usage:
upper()

参数

描述

该方法没有参数。

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

lower#

lower 将字符串中的所有字母转换为小写。

Usage:
lower()

参数

描述

该方法没有参数。

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

检查子字符串#

in#

in is a keyword that returns a Boolean indicating whether a substring (word or piece of text) exists in a string.

  • True –单词存在于字符串中。

  • False –单词不存在于字符串中。

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

startswith#

startswith 返回一个布尔值,指示字符串是否以给定值开头。

  • True – 该单词位于字符串的开头。

  • False ​​– 该单词不是字符串的开头。

Usage:
startswith(substring)

参数

描述

substring

The substring to check for at the beginning of the string.

message = "AIM Robot"

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

endswith#

endswith 返回一个布尔值,指示字符串是否以给定值结尾。

  • True –单词在字符串结尾。

  • False –单词不在字符串结尾。

用法:
endswith(substring)

参数

描述

substring

The substring to check for at the end of the string.

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)