字符串格式化#
介绍#
Python 中的 .format() 方法用于创建包含变量、表达式或值的字符串。此方法会将字符串中的花括号占位 .format() 替换为 {}内部提供的值。
x = 1
y = 5
# Display the variables using .format()
brain.print("Position: ({}, {})".format(x, y))
# Display a calculation using .format()
brain.print("Sum: {}".format(5 + 3))
wait(1, SECONDS)
# Display the time using .format()
brain.print("Time: {}".format(brain.timer_time(SECONDS)))
使用 .format 格式化数字 – 将值和表达式插入字符串。
:.xf– 设置要显示的小数位数。round– 将数字四舍五入到指定的小数位数。:,– 添加逗号作为千位分隔符。:.x%– 将小数转换为保留 x 位小数的百分比。:#x– 将数字格式化为十六进制。:b– 将数字格式化为二进制。
合并字符串 – 将文本和值合并在一起。
.format()– 在单个表达式中组合字符串和变量。+ operator– 手动连接字符串,并可选择进行类型转换。
字符串方法 – 更改文本的大小写。
检查子字符串 – 测试文本是否存在或位置。
in– 检查字符串中是否存在某个单词。startswith()– 检查字符串是否以给定值开头。endswith()– 检查字符串是否以给定值结尾。
转义序列 – 使用特殊字符格式化输出。
使用 .format#
.format 可用于控制数字的显示方式,包括小数位数、四舍五入以及其他格式样式,例如:
Fixed Decimal Places#
.xf 控制数字显示的小数位数。
Usage:
:.xf
参数 |
描述 |
|---|---|
|
显示的小数位数。 |
# Display pi with 2 decimal places
pi = 3.1415926535
brain.print("Pi: {:.2f}".format(pi))
# Output: Pi: 3.14
Rounding Numbers#
round 在格式化之前将数字四舍五入到指定的小数位数。
Usage:
round(number, x)
参数 |
描述 |
|---|---|
|
要四舍五入的数字。 |
|
四舍五入到小数点后的位数。 |
# Display a value rounded to only 2 decimal places
value = 5.6789
brain.print("Rounded: {}".format(round(value, 2)))
# Output: Rounded: 5.68
Thousands Separator#
:, 插入逗号作为千位分隔符,使大数字更易读。
Usage:
:,
参数 |
描述 |
|---|---|
此格式说明符没有参数。 |
# Display a large number separated with commas
number = 1234567
brain.print("Formatted: ")
brain.print("{:,}".format(number))
# Output: Formatted: 1,234,567
Percentage#
:.x% 将十进制值乘以 100 并添加百分号,从而将十进制值格式化为百分比。
Usage:
:.x%
参数 |
描述 |
|---|---|
|
显示的小数位数。 |
# Display a converted decimal to a percentage
value = 0.875
brain.print("Score: {:.1%}".format(value))
# Output: Score: 87.5%
Hexadecimal#
:#x 将数字转换为十六进制。
Usage:
:#x
参数 |
描述 |
|---|---|
此格式说明符没有参数。 |
# Convert 255 to hexadecimal
number = 255
brain.print("Hex: {:#x}".format(number))
# Output: Hex: 0xff
Binary#
:b 将数字转换为二进制(以 2 为基数)。
Usage:
:b
参数 |
描述 |
|---|---|
此格式说明符没有参数。 |
# Convert 3 to binary
brain.print("Binary: {:b}".format(3))
# Output: Binary: 11
字符串合并#
您可以使用两种方法合并(或连接)字符串:
Using .format#
使用 {}将值直接插入字符串中。
# Display an answer based on the given emotion
emotion = "good"
brain.print("I'm {}, you?".format(emotion))
+ Operator#
使用 +连接多个部分。
注意:非字符串必须先使用 str()
# Display the x and y values
x = 10
y = 20
brain.print("X: " + str(x) + ", Y: " + str(y))
字符串方法#
Python 提供了用于修改和检查字符串的内置方法。
upper#
upper 将字符串中的所有字母转换为大写。
Usage:
upper()
参数 |
描述 |
|---|---|
此方法没有参数。 |
# Capitalize a string with .upper()
message = "vexcode"
brain.print(message.upper()) # Output: VEXCODE
lower#
lower 将字符串中的所有字母转换为小写。
Usage:
lower()
参数 |
描述 |
|---|---|
此方法没有参数。 |
# Make a string lowercase with .lower()
message = "VEXCODE"
brain.print(message.lower()) # Output: vexcode
检查子字符串#
in#
in 是一个关键字,它返回一个布尔值,指示子字符串(单词或文本片段)是否存在于字符串中。
True– 该单词存在于字符串中。False– 该单词在字符串中不存在。
message = "Hey everyone!"
if "Hey" in message:
brain.print("Hello!")
startswith#
startswith 返回一个布尔值,指示字符串是否以给定值开头。
True– 该单词位于字符串的开头。False– 该单词不是字符串的开头。
Usage:
startswith(substring)
参数 |
描述 |
|---|---|
|
要检查的子字符串是否位于字符串的开头。 |
# Check for 'CTE' at the start of a string
message = "CTE Robot"
if message.startswith("CTE"):
brain.print("CTE first!")
endswith#
endswith 返回一个布尔值,指示字符串是否以给定值结尾。
True– 该单词结束字符串。False– 该单词未结束字符串。
Usage:
endswith(substring)
参数 |
描述 |
|---|---|
|
要检查的字符串末尾的子字符串。 |
# Check for `Robot` at the end of a string
message = "CTE Robot"
if message.endswith("Robot"):
brain.print("Robot last!")
转义序列#
转义序列是字符串中用于格式化文本输出的特殊字符。
New Line#
\n 在打印时将文本移至新行。
# Display text on two lines
brain.print("First line\nSecond line")
Tab Spacing#
\t 在单词或数字之间插入制表符空格。
# Display the quantity of disks
quantity = 2
brain.print("Disks:\t", quantity)