Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using string interpolation, how to pad with a given character?

Tags:

c#

c#-6.0

I know I'm in danger here, but couldn't find in SO/Google:

Using string interpolation, how do I pad with a given character? for instance:

foreach (var p in people) {
    Console.WriteLine($"{p.Name,-10}: {p.Age}");
}

Will result in (e.g.):

Joe       : 26
Dan       : 52

How do I change the spaces with dots, via string interpolation? to get:

Joe.......: 26
Dan.......: 52

(I know I can do p.Name.PadRight(10,'.'), but I'm pretty sure there's a way with string-interpolation parameters, like the padding length).

like image 516
Tar Avatar asked Oct 16 '18 17:10

Tar


People also ask

How do you add padding to a string?

The standard way to add padding to a string in Python is using the str. rjust() function. It takes the width and padding to be used. If no padding is specified, the default padding of ASCII space is used.

Which character should be used for string interpolation?

To identify a string literal as an interpolated string, prepend it with the $ symbol. You can't have any white space between the $ and the " that starts a string literal. The expression that produces a result to be formatted.

How do you add padding to a string in Java?

Use the String. format() method to pad the string with spaces on left and right, and then replace these spaces with the given character using String. replace() method. For left padding, the syntax to use the String.

How is string interpolation performed?

String interpolation is a process of injecting value into a placeholder (a placeholder is nothing but a variable to which you can assign data/value later) in a string literal. It helps in dynamically formatting the output in a fancier way. Python supports multiple ways to format string literals.


2 Answers

@Tar why dont you try this:

var paddingWithChar = new string ('.', lengthOfPaddingAsInt); 

Console.WriteLine ($"{p.Name}{paddingWithChar}:{p.Age,10}");
like image 136
FreedomOfSpeech Avatar answered Oct 21 '22 10:10

FreedomOfSpeech


Browsing through Microsoft's Docs for the alignment component for string formatting, I found this little excerpt.

If padding is necessary, white space is used.

You're stuck with whitespace if you're going to use string interpolation. As you noted earlier, string.PadRight() will suffice as a workaround.

like image 37
AntiTcb Avatar answered Oct 21 '22 11:10

AntiTcb