首页 > 解决方案 > Rust 相当于 Python 的 ljust() 字符串方法

问题描述

我需要&str在 Rust 中左对齐 a。

在 Python 中,我会这样做:

f"{spam}: {eggs}".ljust(curses.COLS - 1)

我如何在 Rust 中惯用地做到这一点?

标签: pythonrust

解决方案


格式化宏,例如println!,write!format!提供此功能。看看https://doc.rust-lang.org/std/fmt/#fillalignmenthttps://doc.rust-lang.org/std/fmt/#width

  • {:5}指定最小宽度为 5
  • {:-<5}左对齐到五位数并填充-
  • {1:0$}:“宽度的值也可以通过添加后缀$来作为参数列表中的usize提供,表示第二个参数是指定宽度的usize。”

推荐阅读