Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format strings with indentation based on an integer?

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?

like image 506
ideasman42 Avatar asked Feb 16 '17 12:02

ideasman42


People also ask

How strings are displayed with different formats?

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.

What is str format () in Python?

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.

What is return by format () method?

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.


1 Answers

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);
like image 66
Lukas Kalbertodt Avatar answered Sep 30 '22 17:09

Lukas Kalbertodt