Format a Go string without printing?
Answer recommended by Go Language
Answer recommended by Go Language
Try this approach using the newer str.format syntax: line_new = ‘{:>12} {:>12} {:>12}’.format(word[0], word[1], word[2]) And here’s how to do it using the old % syntax (useful for older versions of Python that don’t support str.format): line_new = ‘%12s %12s %12s’ % (word[0], word[1], word[2])
Sorry for reactivating this question, but I didn’t find the right answer here. In formatting numbers you can use 0 as a mandatory place and # as an optional place. So: // just two decimal places String.Format(“{0:0.##}”, 123.4567); // “123.46” String.Format(“{0:0.##}”, 123.4); // “123.4” String.Format(“{0:0.##}”, 123.0); // “123” You can also combine 0 with #. … Read more
The datetime class has a method strftime. The Python docs documents the different formats it accepts: Python 2: strftime() Behavior Python 3: strftime() Behavior For this specific example, it would look something like: my_datetime.strftime(“%B %d, %Y”)
It is a string formatting syntax (which it borrows from C). Please see “PyFormat”: Python supports formatting values into strings. Although this can include very complicated expressions, the most basic usage is to insert values into a string with the %s placeholder. Here is a really simple example: #Python 2 name = raw_input(“who are you? … Read more
from decimal import Decimal ‘%.2E’ % Decimal(‘40800000000.00000000000000’) # returns ‘4.08E+10′ In your ‘40800000000.00000000000000’ there are many more significant zeros that have the same meaning as any other digit. That’s why you have to tell explicitly where you want to stop. If you want to remove all trailing zeros automatically, you can try: def format_e(n): a=”%E” … Read more
Use System.out.format . You can set lengths of fields like this: System.out.format(“%32s%10d%16s”, string1, int1, string2); This pads string1, int1, and string2 to 32, 10, and 16 characters, respectively. See the Javadocs for java.util.Formatter for more information on the syntax (System.out.format uses a Formatter internally).
You should use the new format specifications to define how your value should be represented: >>> from math import pi # pi ~ 3.141592653589793 >>> ‘{0:.2f}’.format(pi) ‘3.14’ The documentation can be a bit obtuse at times, so I recommend the following, easier readable references: the Python String Format Cookbook: shows examples of the new-style .format() … Read more
Take a look at String.format. Note, however, that it takes format specifiers similar to those of C’s printf family of functions — for example: String.format(“Hello %s, %d”, “world”, 42); Would return “Hello world, 42”. You may find this helpful when learning about the format specifiers. Andy Thomas-Cramer was kind enough to leave this link in … Read more
I think this is a suboptimal solution, but you could do String.format(“%16s”, Integer.toBinaryString(1)).replace(‘ ‘, ‘0’)