Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take next parameter as field width in String.Format

In C#, I have a width I want to use for some strings, but I won't know that width until runtime. I'm doing something like this:

string.Format("{0, " + digits + "}", value)  // prints 123 as "  123"

Is there a string formatting directive that lets me specify this without smashing my own format string together like this?

I looked around on MSDN for a little while and I feel like I'm missing a whole chapter on format strings or something.

like image 491
Ken Avatar asked Feb 22 '10 21:02

Ken


People also ask

How do you print a fixed width string?

Save this question. Show activity on this post. def splitter(str): for i in range(1, len(str)): start = str[0:i] end = str[i:] yield (start, end) for split in splitter(end): result = [start] result.

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.

How do you write in string format?

In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string. Parameter: The locale value to be applied on the format() method.

How do you print a string at a fixed width in Python?

Use a formatted string literal to print a string at a fixed width, e.g. print(f'{my_str: <6}') . You can use an expression inside of a formatted string literal where you can specify the width of the string and the alignment. Copied!


1 Answers

Take a look at PadLeft:

s = "123".PadLeft(5);  // Defaults to spaces
s = "123".PadLeft(5, '.');  // Pads with dots
like image 193
Michael Bray Avatar answered Nov 06 '22 11:11

Michael Bray