Is there a better way to print/format string indentation besides doing:
let text_to_indent = "Indented text!";
for i in 0..indent {
print!(" ");
}
println!("{}", text_to_indent);
Does Rust have a more convenient way to do this?
Format Specifiers Used in C %c :char single character. %d (%i) :int signed integer. %e (%E) :float or double exponential format. %f :float or double signed decimal.
Python's str. format() method of the string class allows you to do variable substitutions and value formatting. This lets you concatenate elements together within a string through positional formatting.
format() method returns the formatted string by a given locale, format, and argument. If the locale is not specified in the String. format() method, it uses the default locale by calling the Locale.
println!("{:indent$}Indented text!", "", indent=indent);
(Playground)
The first placeholder does the indentation. It will print the argument 0 (empty string, ""
) with a padding (with spaces) as specified in argument ident
.
Printing a variable can be done like this:
println!("{:indent$}{}", "", text_to_indent, indent=level);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With