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).
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.
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.
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.
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.
@Tar why dont you try this:
var paddingWithChar = new string ('.', lengthOfPaddingAsInt);
Console.WriteLine ($"{p.Name}{paddingWithChar}:{p.Age,10}");
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.
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