# 示例代码:使用 % 进行字符串格式化
# 1. 基本用法
name = "Alice"
age = 30
formatted_string = "My name is %s and I am %d years old." % (name, age)
print(formatted_string) # 输出: My name is Alice and I am 30 years old.
# 2. 格式化浮点数
pi = 3.1415926
formatted_pi = "The value of pi is approximately %.2f" % pi
print(formatted_pi) # 输出: The value of pi is approximately 3.14
# 3. 使用字典进行格式化
data = {'first': 'John', 'last': 'Doe'}
formatted_name = "Name: %(first)s %(last)s" % data
print(formatted_name) # 输出: Name: John Doe
# 4. 使用 % 进行取模运算
result = 10 % 3
print(result) # 输出: 1
% 在 Python 中有两种主要用途:%s 表示字符串,%d 表示整数,%.2f 表示保留两位小数的浮点数。10 % 3 的结果是 1。上一篇:base64 python
下一篇:python keyboard库
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站