字符串格式#

简介#

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}”] (#introduction) –显示字符串内的变量、表达式或函数调用。

设置f字符串中的数字格式–控制数值的显示方式。

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

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

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

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

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

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

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

  • f”{value}” –在单个表达式中组合字符串和变量。

  • + operator –使用可选类型转换手动连接字符串。

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

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

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

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

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

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

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

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

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

  • \t –在项目之间添加选项卡空间。

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

f-strings 允许通过使用以下格式说明符,来精确控制小数位数、四舍五入、千位分隔符等等:

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

要检查的子字符串是否位于字符串的开头。

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)