当前位置: 首页 > java >正文

【Python基础】 18 Rust 与 Python print 函数完整对比笔记

一、Rust println! 宏

基本语法

// 基本输出
println!("Hello, World!");// 格式化输出
let name = "Alice";
let age = 25;
println!("Name: {}, Age: {}", name, age);// 带位置参数的输出
println!("{0} is {1} years old. {0} is a programmer.", name, age);// 带命名参数的输出
println!("Name: {name}, Age: {age}", name = name, age = age);
格式化选项
let number = 42;
let float = 3.14159;
let text = "hello";// 数字格式化
println!("Decimal: {}", number);          // 42
println!("Hex: {:x}", number);            // 2a
println!("Binary: {:b}", number);         // 101010
println!("Octal: {:o}", number);          // 52// 浮点数格式化
println!("Float: {}", float);             // 3.14159
println!("2 decimals: {:.2}", float);     // 3.14
println!("Scientific: {:e}", float);      // 3.14159e0// 字符串格式化
println!("Text: {}", text);               // hello
println!("Right align: {:>10}", text);    //      hello
println!("Left align: {:<10}", text);     // hello     
println!("Center: {:^10}", text);         //   hello   
println!("Fill: {:_<10}", text);          // hello_____// 特殊格式
println!("Pointer: {:p}", &number);       // 内存地址
println!("Debug: {:?}", (number, text));  // (42, "hello")
println!("Pretty debug: {:#?}", vec![1, 2, 3]); // 格式化输出
错误输出
// 输出到标准错误
eprintln!("Error: Something went wrong!");
eprintln!("Error value: {}", 42);

二、Python print 函数

基本语法
# 基本输出
print("Hello, World!")# 多个参数
name = "Alice"
age = 25
print("Name:", name, "Age:", age)# 格式化输出
print(f"Name: {name}, Age: {age}")          # f-string (3.6+)
print("Name: {}, Age: {}".format(name, age)) # str.format()
print("Name: %s, Age: %d" % (name, age))    # %-formatting
参数详解
# sep 参数 - 分隔符
print("a", "b", "c")                 # a b c
print("a", "b", "c", sep="-")        # a-b-c
print("a", "b", "c", sep="")         # abc# end 参数 - 结束符
print("Hello", end=" ")              # Hello (不换行)
print("World")                       # Hello World# file 参数 - 输出到文件
with open("output.txt", "w") as f:print("Hello File", file=f)# flush 参数 - 强制刷新缓冲区
import time
print("Loading", end="", flush=True)
time.sleep(1)
print("...Done")
格式化选项
number = 42
float_num = 3.14159
text = "hello"# 数字格式化
print(f"Decimal: {number}")           # 42
print(f"Hex: {number:x}")             # 2a
print(f"Binary: {number:b}")          # 101010
print(f"Octal: {number:o}")           # 52# 浮点数格式化
print(f"Float: {float_num}")          # 3.14159
print(f"2 decimals: {float_num:.2f}") # 3.14
print(f"Scientific: {float_num:e}")   # 3.141590e+00# 字符串格式化
print(f"Text: {text}")                # hello
print(f"Right align: {text:>10}")     #      hello
print(f"Left align: {text:<10}")      # hello     
print(f"Center: {text:^10}")          #   hello   
print(f"Fill: {text:_<10}")           # hello_____# 千分位分隔符
big_number = 123456789
print(f"With commas: {big_number:,}") # 123,456,789
错误输出
import sys# 输出到标准错误
print("Error: Something went wrong!", file=sys.stderr)
sys.stderr.write("Error message\n")

三、转义字符列表

通用转义字符
转义字符说明Rust 示例Python 示例
\n换行println!("Line 1\nLine 2");print("Line 1\nLine 2")
\t制表符println!("Name:\tAlice");print("Name:\tAlice")
\\反斜杠println!("Path: C:\\Windows");print("Path: C:\\Windows")
\"双引号println!("He said: \"Hello\"");print("He said: \"Hello\"")
\'单引号println!("It\'s mine");print("It\'s mine")
\r回车println!("Loading...\rDone");print("Loading...\rDone")
\0空字符println!("End\0of string");print("End\0of string")
Rust 特有转义字符
// 原始字符串 - 忽略转义字符
println!(r"C:\Windows\System32"); // C:\Windows\System32// 多行原始字符串
println!(r#"This is amulti-lineraw string
"#);// Unicode 转义
println!("\u{1F600}"); // 😀
println!("\u{1F47E}"); // 👾// 字节字符串
println!(b"Hello"); // 输出字节数组
Python 特有转义字符
# 原始字符串
print(r"C:\Windows\System32")  # C:\Windows\System32# 多行字符串
print("""
Line 1
Line 2
Line 3
""")# Unicode 转义
print("\N{GRINNING FACE}")     # 😀
print("\U0001F47E")            # 👾
print("\u03A9")                # Ω# 其他转义
print("\a")  # 响铃 (可能不工作)
print("\f")  # 换页符
print("\v")  # 垂直制表符

四、高级用法对比

Rust 高级输出
use std::io::{self, Write};// 手动刷新缓冲区
print!("Loading...");
io::stdout().flush().unwrap(); // 立即输出
std::thread::sleep(std::time::Duration::from_secs(1));
println!(" Done");// 格式化复杂数据结构
#[derive(Debug)]
struct Person {name: String,age: u32,
}let person = Person { name: "Bob".to_string(), age: 30 };
println!("{:#?}", person); // 漂亮打印// 自定义格式化
use std::fmt;impl fmt::Display for Person {fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {write!(f, "{} ({} years old)", self.name, self.age)}
}println!("{}", person); // Bob (30 years old)
Python 高级输出
import json
from dataclasses import dataclass# 输出到字符串
output = "Hello"
print(str(output))      # Hello
print(repr(output))     # 'Hello'# JSON 格式化输出
data = {"name": "Alice", "age": 25}
print(json.dumps(data, indent=2))
# {
#   "name": "Alice",
#   "age": 25
# }# 使用 dataclass
from dataclasses import dataclass@dataclass
class Person:name: strage: intperson = Person("Bob", 30)
print(person)  # Person(name='Bob', age=30)# 进度条效果
import time
for i in range(101):print(f"\rProgress: {i}%", end="", flush=True)time.sleep(0.1)
print()

五、性能考虑

Rust 性能优化
// 避免频繁分配 - 使用 write! 宏
use std::io::{self, Write};let mut output = String::new();
write!(&mut output, "Hello, {}!", "world").unwrap();
println!("{}", output);// 批量输出
let lines = vec!["Line 1", "Line 2", "Line 3"];
for line in lines {println!("{}", line);
}// 或者使用 join
println!("{}", lines.join("\n"));
Python 性能优化
# 避免频繁的 print 调用
lines = ["Line 1", "Line 2", "Line 3"]# 不好:多次 IO 操作
for line in lines:print(line)# 更好:单次 IO 操作
print("\n".join(lines))# 使用 StringIO 进行内存中的字符串构建
from io import StringIO
output = StringIO()
output.write("Hello, ")
output.write("world!")
print(output.getvalue())

六、跨平台注意事项

Rust 跨平台输出
// 处理不同平台的换行符
#[cfg(windows)]
const NEWLINE: &str = "\r\n";#[cfg(not(windows))]
const NEWLINE: &str = "\n";println!("Line 1{}Line 2", NEWLINE);// 或者使用 std::env::consts::LINE_SEPARATOR
Python 跨平台输出
import os# 跨平台换行符
print("Line 1", "Line 2", sep=os.linesep)# 或者让 Python 自动处理
print("Line 1")
print("Line 2")# 处理编码问题
import sys
if sys.stdout.encoding != 'UTF-8':sys.stdout.reconfigure(encoding='utf-8')

七、总结对比

特性Rust 🦀Python 🐍
语法宏:println!(), print!()函数:print()
格式化编译时检查,类型安全运行时检查,灵活
性能零成本抽象,高性能有运行时开销
错误处理编译时错误检查运行时异常
灵活性相对严格非常灵活
学习曲线较陡峭平缓
适用场景系统编程,高性能应用脚本,快速开发
选择建议:
  • 选择 Rust:需要高性能、内存安全、系统级输出控制
  • 选择 Python:需要快速开发、灵活格式化、简单脚本

关键记忆点:

  • Rust 使用宏,Python 使用函数
  • Rust 编译时检查格式化,Python 运行时检查
  • 两者都支持相似的转义字符
  • Python 有更多输出选项(sep, end, file, flush)
  • Rust 有更好的性能特性
http://www.xdnf.cn/news/20225.html

相关文章:

  • 通过Gen AI SDK调用gemini 2.5 pro,单独上传pdf文件 | ai agent 开发笔记 2025.9.2 Day 2
  • 确保 SQL Server 备份安全有效的最佳实践
  • 【面试场景题】spring应用启动时出现内存溢出怎么排查
  • Nginx 高性能调优指南:从配置到原理
  • 用 Cursor AI 快速开发你的第一个编程小程序
  • Sentinel和Cluster,到底该怎么选?
  • 2025高教社数学建模国赛A题 - 烟幕干扰弹的投放策略(完整参考论文)
  • 【Tailwind, Daisyui】响应式表格 responsive table
  • 一文教您学会Ubuntu安装Pycharm
  • 管家婆分销ERP A/V系列导出提示加载数据过大的处理方式
  • 【Python基础】 17 Rust 与 Python 运算符对比学习笔记
  • k8s除了主server服务器可正常使用kubectl命令,其他节点不能使用原因,以及如何在其他k8s节点正常使用kubectl命令??
  • 人工智能机器学习——聚类
  • 2025 汽车租赁大会:九识智能以“租赁+运力”革新城市智能配送
  • 指定端口-SSH连接的目标(告别 22 端口暴力破解)
  • 结构体简介
  • window cmd 命令行中指定代理
  • 对于单链表相关经典算法题:203. 移除链表元素的解析
  • 数据结构:栈和队列力扣算法题
  • 空域属不属于自然资源?(GPT5)
  • Redis-事务与管道
  • 使用CI/CD部署后端项目(gin)
  • 因泰立科技:用激光雷达重塑智能工厂物流生态
  • 【网安基础】--ip地址与子网掩码
  • 告别线缆束缚!AirDroid Cast 多端投屏,让分享更自由
  • 编写后端JAR包蓝绿发布脚本
  • 23种设计模式——代理模式(Proxy Pattern)详解
  • 【使用goto统计输入数的奇偶数量】2022-10-28
  • 人工智能时代职能科室降本增效KPI设定全流程与思路考察
  • 【高分论文密码】大尺度空间模拟与不确定性分析及数字制图技术应用