Format a Go string without printing?
Sprintf is what you are looking for. Example fmt.Sprintf(“foo: %s”, bar) You can also see it in use in the Errors example as part of “A Tour of Go.” return fmt.Sprintf(“at %v, %s”, e.When, e.What)
Sprintf is what you are looking for. Example fmt.Sprintf(“foo: %s”, bar) You can also see it in use in the Errors example as part of “A Tour of Go.” return fmt.Sprintf(“at %v, %s”, e.When, e.What)
Formatting and Styling Yes, see the following from String Resources: Formatting and Styling If you need to format your strings using String.format(String, Object…), then you can do so by putting your format arguments in the string resource. For example, with the following resource: <string name=”welcome_messages”>Hello, %1$s! You have %2$d new messages.</string> In this example, the … Read more
You can do this with str.ljust(width[, fillchar]): Return the string left justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s). >>> ‘hi’.ljust(10) ‘hi ‘
In Python 2 (and Python 3) you can do: number = 1 print(“%02d” % (number,)) Basically % is like printf or sprintf (see docs). For Python 3.+, the same behavior can also be achieved with format: number = 1 print(“{:02d}”.format(number)) For Python 3.6+ the same behavior can be achieved with f-strings: number = 1 print(f”{number:02d}”)
To answer your first question… .format just seems more sophisticated in many ways. An annoying thing about % is also how it can either take a variable or a tuple. You’d think the following would always work: “Hello %s” % name yet, if name happens to be (1, 2, 3), it will throw a TypeError. … Read more
You need to double the {{ and }}: >>> x = ” {{ Hello }} {0} ” >>> print(x.format(42)) ‘ { Hello } 42 ‘ Here’s the relevant part of the Python documentation for format string syntax: Format strings contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is … Read more