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

一、Rust println! 宏

基本语法

rust 复制代码
// 基本输出
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);
格式化选项
rust 复制代码
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]); // 格式化输出
错误输出
rust 复制代码
// 输出到标准错误
eprintln!("Error: Something went wrong!");
eprintln!("Error value: {}", 42);

二、Python print 函数

基本语法
python 复制代码
# 基本输出
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
参数详解
python 复制代码
# 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")
格式化选项
python 复制代码
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
错误输出
python 复制代码
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 特有转义字符
rust 复制代码
// 原始字符串 - 忽略转义字符
println!(r"C:\Windows\System32"); // C:\Windows\System32

// 多行原始字符串
println!(r#"
    This is a
    multi-line
    raw string
"#);

// Unicode 转义
println!("\u{1F600}"); // 😀
println!("\u{1F47E}"); // 👾

// 字节字符串
println!(b"Hello"); // 输出字节数组
Python 特有转义字符
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 高级输出
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 高级输出
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: str
    age: int

person = 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 性能优化
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 性能优化
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 跨平台输出
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 跨平台输出
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 有更好的性能特性
相关推荐
大模型真好玩3 小时前
大模型工程面试经典(五)—大模型专业领域微调数据集如何构建?
人工智能·python·面试
UrbanJazzerati3 小时前
Python正则表达式匹配和替换详细指南
python·面试
怒码ing3 小时前
List<?>和List<Object>区别
windows·python·list
那雨倾城3 小时前
PiscCode轨迹跟踪Mediapipe + OpenCV进阶:速度估算
图像处理·人工智能·python·opencv·计算机视觉
闻道且行之3 小时前
嵌入式|Linux中打开视频流的两种方式V4l2和opencv
linux·笔记·opencv·嵌入式
2501_920047034 小时前
bash自带的切片操作
开发语言·python·bash
偷心伊普西隆4 小时前
Python EXCEL 小技巧:最快重新排列dataframe函数
python·excel
于顾而言4 小时前
【笔记】Software Engineering at Google
笔记·log4j·软件工程
我是海飞4 小时前
Tensorflow Lite 的yes/no语音识别音频预处理模型训练教程
python·学习·tensorflow·音视频·嵌入式·语音识别