1

I'm loading a JSON and I'm printing string formatting.

fmt = (u"{id:<4} {title:<28} {timestamp:<23} {description:<23}"
       u" {link}")

and to print:

for item in items
    print(fmt.format(**item))

This works fine. But the problem here is that I'm printing a unix timestamp.

Now I've written a function (convert_unix_timestamp)which converts the unix timestamp to a readable timestamp.

But how can I use this function and also use my string formatting?

I was thinking about something as below but I don't know how to make this work

fmt = (u"{id:<4} {title:<28} {self.convert_unix_timestamp(timestamp):<23} {description:<23}"
       u" {link}")

Can someone tell me how I can use a function inside this above?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
DenCowboy
  • 13,884
  • 38
  • 114
  • 210
  • This isn't a click question. You pass the result of `str.format()` to click, this is a *string formatting* question. – Martijn Pieters Mar 07 '18 at 21:46
  • See https://docs.python.org/3/library/string.html#format-string-syntax for what is possible with the syntax. – Martijn Pieters Mar 07 '18 at 21:47
  • In this case, just update the dictionary first, or copy the dictionary and then update the value with the function. – Martijn Pieters Mar 07 '18 at 21:50
  • If you are using Python 3.6, use [formated string literals](https://docs.python.org/3/reference/lexical_analysis.html#f-strings) instead. – Martijn Pieters Mar 07 '18 at 21:50
  • Also, if this really is Python 3 as your question tag suggests, then the `u` prefixes to the string literals are redundant. They are only needed in Python 2 or code that needs to remain compatible with Python 2. – Martijn Pieters Mar 07 '18 at 21:52
  • @MartijnPieters Thanks I'll try to use the formated string literals! And yes, I used python 2.7 a bit in the past, this is the first time I'm trying 3.6, so making some silly mistakes. – DenCowboy Mar 07 '18 at 21:54
  • Although, you are using a format string in a variable; `f` strings produce the formatted result when executed, not via a separate `.format()` method call. If you need to be able to swap out format strings then an `f` string won’t be suitable. – Martijn Pieters Mar 07 '18 at 22:06

0 Answers0