字符串格式化#

简介#

在 Python 中,格式化文本和数字的推荐方式是使用 f-字符串。它们允许将变量、表达式和函数调用直接嵌入 {} 中。

要创建f字符串,请在字符串f 之前添加,并在 {}中放置任何变量、表达式或函数调用。

x = 1
y = 5

# Display the variables using an f-string
controller.screen.print(f"Position: ({x}, {y})")

# Display a calculation with an f-string
controller.screen.print(f"Sum: {5 + 3}")

# Display the robot's battery capacity with an f-string
controller.screen.print(f"Battery: {controller.get_battery_level()}%")

f-strings –直接在文本中嵌入变量和表达式。

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

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

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

  • round –将数字舍入到给定的小数位数。

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Fixed Decimal Places#

.xf 控制数字显示时的小数位数。

用法:
.xf

参数

描述

x

要显示的小数位数。

# Display pi with 2 decimal places
pi = 3.1415926535
controller.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
controller.screen.print(f"{round(value, 2)}")

# Output: 5.68

Thousands Separator#

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

用法:
,

参数

描述

此格式说明符没有参数。

# Display a large number separated with commas
number = 1234567
controller.screen.print(f"{number:,}")

# Output: 1,234,567

Percentage#

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

用法:
.x%

参数

描述

x

要显示的小数位数。

# Display a converted decimal to a percentage
value = 0.875

controller.screen.print(f"{value:.1%}")

# Output: 87.5%

Hexadecimal#

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

用法:
.#x

参数

描述

此格式说明符没有参数。

# Convert 255 to hexadecimal
number = 255

controller.screen.print(f"{number:#x}")

# Output: 0xff

Binary#

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

用法:
b

参数

描述

此格式说明符没有参数。

# Convert 3 to binary
controller.screen.print(f"Binary: {3:b}")

# Output: Binary: 11

组合字符串#

您可以使用两种方法来组合(或连接)字符串:

Using f-strings#

使用f字符串,您可以直接在{}中嵌入变量。

# Display an answer based on the given emotion
emotion = "good"

controller.screen.print(f"I'm {emotion}, you?")

+ Operator#

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

注:非字符串必须首先使用 str() 转换为字符串。

# Display the x and y values
x = 10
y = 20

controller.screen.print("X: " + str(x) + ", Y: " + str(y))

字符串方法#

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

upper#

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

用法:
upper()

参数

描述

该方法没有参数。

# Display a message in uppercase
message = "vexcode"

controller.screen.print(message.upper())

# Output: VEXCODE

lower#

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

用法:
lower()

参数

描述

该方法没有参数。

# Display a message in lowercase
message = "VEXCODE"

controller.screen.print(message.lower())

# Output: vexcode

检查子字符串#

in#

in 是一个关键字,它返回一个布尔值,指示字符串中是否存在某个子字符串(单词或文本片段)。

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

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

# Display a message if "Hey" is in the string
message = "Hey everyone!"

if "Hey" in message:
    controller.screen.print("Hello!")

startswith#

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

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

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

用法:
startswith(substring)

参数

描述

substring

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

# Display a message if the string starts with "AIR"
message = "AIR Drone"

if message.startswith("AIR"):
    controller.screen.print("AIR first!")

endswith#

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

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

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

用法:
endswith(substring)

参数

描述

substring

要检查的字符串末尾的子字符串。

# Display a message if the string ends with "Drone"
message = "AIR Drone"

if message.endswith("Drone"):
    controller.screen.print("Drone 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("IDs:\t", quantity)