字符串格式化#

介绍#

The .format() method in Python is used to create strings that include variables, expressions, or values. This method replaces curly brace placeholders {} in a string with values provided inside .format().

x = 1
y = 5

# Display the variables using .format()
brain.screen.print("Position: ({}, {})".format(x, y))

# Display a calculation using .format()
brain.screen.print("Sum: {}".format(5 + 3))

# Display the robot's battery capacity using .format()
brain.screen.print("Battery: {}%".format(brain.battery.capacity()))

Formatting Numbers with .format — Insert values and expressions into a string.

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

Colors — Change the color of text in the Console

  • Colors — Set the text color of the Console.

Combining Strings — Combine text and values.

  • .format() — Combine strings and variables in a single expression.

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

Checking for Substrings — 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.

Formatting Numbers with .format#

.format can be used to control how numbers appear, including decimal places, rounding, and other formatting styles such as:

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

Rounding Numbers#

round rounds a number to a specific number of decimal places before formatting.

Usage:
round(number, x)

参数

描述

number

要舍入的数字。

x

要四舍五入的小数位数。

# Display a value rounded to only 2 decimal places
value = 5.6789
brain.screen.print("Rounded: {}".format(round(value, 2)))
# Output: Rounded: 5.68

Thousands Separator#

:, inserts commas as thousands separators to make large numbers more readable.

Usage:
:,

参数

描述

此格式说明符没有参数。

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

Percentage#

:.x% formats decimal values as percentages.

Usage:
:.x%

参数

描述

x

要显示的小数位数。

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

Hexadecimal#

:#x converts numbers to hexadecimal.

Usage:
:#x

参数

描述

此格式说明符没有参数。

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

Binary#

:b converts numbers to binary (base 2).

Usage:
:b

参数

描述

此格式说明符没有参数。

# Convert 3 to binary
brain.screen.print("Binary: {:b}".format(3))
# Output: Binary: 11

颜色#

您可以使用以下颜色代码更改打印到打印控制台时文本的颜色:

  • [31m — Red

  • [32m — Green

  • [34m — Blue

  • [30m — Black

  • [37m — White

  • [33m — Yellow

  • [91m — Orange

  • [35m — Purple

  • [36m — Cyan

  • [97m — Transparent

All color codes need to follow an escape sequence = \033 in order to function.

You can use this directly in a print command with a string.

# Print VEXcode in Red to the Print Console
print("\033[31mVEXcode")

You can also use it on its own to set all print commands afterwards to the set color.

# Set the Print Console text color to Red before printing
print("\033[31m")
print("VEXcode")

组合字符串#

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

Using .format#

Insert values directly into the string using {}.

# Display an answer based on the given emotion
emotion = "good"
brain.screen.print("I'm {}, you?".format(emotion))

+ Operator#

Join multiple parts by using +.

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

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

字符串方法#

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

upper#

upper converts all letters in a string to uppercase.

Usage:
upper()

参数

描述

该方法没有参数。

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

lower#

lower converts all letters in a string to lowercase.

Usage:
lower()

参数

描述

该方法没有参数。

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

检查子字符串#

in#

in is a keyword that returns a Boolean indicating whether a word exists in a string.

  • True — The word exists in the string.

  • False — The word does not exist in the string.

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

startswith#

startswith returns a Boolean indicating whether a string begins with a given value.

  • True — The word starts the string.

  • False — The word does not start the string.

Usage:
startswith(substring)

参数

描述

substring

要在字符串内检查的子字符串。

message = "AIM Robot"

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

endswith#

endswith returns a Boolean indicating whether a string ends with a given value.

  • True — The word ends the string.

  • False — The word does not end the string.

Usage:
endswith(substring)

参数

描述

substring

要在字符串内检查的子字符串。

message = "AIM Robot"

if message.endswith("Robot"):
    brain.screen.print("Robot last!")

转义序列#

转义序列是字符串中用于格式化文本输出的特殊字符。它们适用于控制台。

New Line#

\n moves text to a new line when printing.

# Display text on two lines
print("First line\nSecond line")

Tab Spacing#

\t inserts a tab space between words or numbers.

# Display the quantity of blocks
quantity = 2
print("Blocks:\t", quantity)