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