Output single character in C

yes, %c will print a single char: printf(“%c”, ‘h’); also, putchar/putc will work too. From “man putchar”: #include <stdio.h> int fputc(int c, FILE *stream); int putc(int c, FILE *stream); int putchar(int c); * fputc() writes the character c, cast to an unsigned char, to stream. * putc() is equivalent to fputc() except that it may … Read more

Leaving values blank if not passed in str.format

You can follow the recommendation in PEP 3101 and use a subclass Formatter: import string class BlankFormatter(string.Formatter): def __init__(self, default=””): self.default=default def get_value(self, key, args, kwds): if isinstance(key, str): return kwds.get(key, self.default) else: return string.Formatter.get_value(key, args, kwds) kwargs = {“name”: “mark”, “adj”: “mad”} fmt=BlankFormatter() print fmt.format(“My name is {name} and I’m really {adj}.”, **kwargs) # … Read more

How to produce “human readable” strings to represent a TimeSpan

To get rid of the complex if and switch constructs you can use a Dictionary lookup for the correct format string based on TotalSeconds and a CustomFormatter to format the supplied Timespan accordingly. public string GetReadableTimespan(TimeSpan ts) { // formats and its cutoffs based on totalseconds var cutoff = new SortedList<long, string> { {59, “{3:S}” … Read more

advanced string formatting vs template strings

Templates are meant to be simpler than the the usual string formatting, at the cost of expressiveness. The rationale of PEP 292 compares templates to Python’s %-style string formatting: Python currently supports a string substitution syntax based on C’s printf() ‘%’ formatting character. While quite rich, %-formatting codes are also error prone, even for experienced … Read more