I'm using String.format() in Java trying to emulate the printf() control channel available in C. I understand how to specify that a string should be placed in a field which takes 20 characters, 5, 2 ... with 3 decimals, 2, etc. However, the strings are printed right-aligned in their field.
How do I left-align the strings?
Here's an example of a possible output which I would like to modify to left-align EXECUTING
and CREATED
in their fields.
Process PID: 25 Status: ----------- EXECUTING Process PID: 36 Status: READY-SUSPENDED Process PID: 4 Status: ---------------- CREATED
*note: consider '-' as an empty space
Alignment of Strings Using the format() Method in Python For the alignment of strings, we use the same syntax we used for the alignment of numbers. To left-align a string, we use the “:<n” symbol inside the placeholder. Here n is the total length of the required output string.
The Java String. 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.
System. out. printf( "%-15s %15s %n", heading1, heading2); To get the left-justified column, you need a percentage symbol, a minus symbol, the number of characters, and then the letter "s" (lowercase).
Text Alignment You can align values within a specified length of text by using the < , > , or ^ symbols to specify left align, right align, or centering, respectively. Then you follow the those symbols with a character width you desire.
Same way as with printf -- use a -
modifier in the format
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