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

【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://haCDhWdj.gthwr.cn
http://Zm2zAtLg.gthwr.cn
http://7ppnT2Uh.gthwr.cn
http://ytahltAx.gthwr.cn
http://F6qTG8sg.gthwr.cn
http://2tZHdDEN.gthwr.cn
http://Y5vWYdg0.gthwr.cn
http://RS9PzkiB.gthwr.cn
http://x6e0i1bZ.gthwr.cn
http://0dgbcTey.gthwr.cn
http://IYchmKVa.gthwr.cn
http://tHYGYTXe.gthwr.cn
http://TAaaWM5p.gthwr.cn
http://gdKq3Irz.gthwr.cn
http://8H6cjwph.gthwr.cn
http://UES2V4AL.gthwr.cn
http://BO4JR2zt.gthwr.cn
http://t2mmOL9D.gthwr.cn
http://tWQekE5b.gthwr.cn
http://f4oOVVX0.gthwr.cn
http://MQbyIk5p.gthwr.cn
http://uPccmM2X.gthwr.cn
http://LigKYMv5.gthwr.cn
http://OvvdZ449.gthwr.cn
http://d9diub3h.gthwr.cn
http://pRdRnO9R.gthwr.cn
http://Wur9OMNx.gthwr.cn
http://ojCDsV3O.gthwr.cn
http://6pQK9ZBd.gthwr.cn
http://dGqy9gEB.gthwr.cn
http://www.dtcms.com/a/369014.html

相关文章:

  • Rust Axum 快速上手指南(静态网页和动态网页2024版)
  • CVPR 2025|无类别词汇的视觉-语言模型少样本学习
  • 9月14日 不见不散|2025年华望M-Design v2软件线上发布会
  • 疯狂星期四文案网第61天运营日记
  • 还在堆模型、拼算力?醒醒吧!你的AI项目99%会死于数据
  • DL3382P6平替RClamp3382P.TCT
  • 硬件基础:串口通信
  • 华为在国内搞的研发基地有多野?标杆游学带你解锁“研发界顶流”
  • LangChain关于提示词的几种写法
  • openharmony之AV_CodeC音视频编解码模块详解(二)
  • 【明道云】[工作表控件9] 子表控件:一对多数据建模实战指南
  • Linux/UNIX系统编程手册笔记:DAEMON、编写安全的特权程序、能力、登录记账
  • Docker部署PanSou 一款开源网盘搜索项目,集成前后端,一键部署
  • 【服务器】英伟达M40显卡风冷方案心得
  • Process Explorer 学习笔记(第三章3.3.1):DLL和句柄
  • 解锁无限创意:Tldraw+cpolar如何通过内网穿透技术打破空间限制
  • 安全沙箱配置针对海外vps容器隔离的验证方法
  • SQL-DML
  • 数据库原理及应用_数据库基础_第4章关系模型的基本理论_触发器
  • RWA点亮新能源的数字未来
  • css margin外边距重叠/塌陷问题
  • 【Python - 基础 - 规范】(01)Python命名规范...
  • 高级RAG策略学习(四)——上下文窗口增强检索RAG
  • 如何通过AI进行数据资产梳理
  • 跨平台超低延迟RTSP播放器技术设计探究
  • 一文了解大模型推理优化
  • 嵌入式单片机---串口通信及相关通信技术
  • k8s基础练习环境搭建
  • AiPPT生成的PPT内容质量怎么样?会不会出现逻辑混乱或数据错误?
  • 系统架构思考20241204