Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I left-align strings using String.format()?

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

like image 821
De La Cuesta Avatar asked Feb 04 '11 00:02

De La Cuesta


People also ask

How do I format a string to the left?

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.

What is string format () used for?

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.

How do you left align a string in Java?

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).

How do you align text in a string in python?

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.


1 Answers

Same way as with printf -- use a - modifier in the format

like image 157
Chris Dodd Avatar answered Oct 06 '22 07:10

Chris Dodd