Search code examples
pythonpython-3.xf-stringpep

How does the f-string in this Python function work?


Hi I found the below function on some website somewhere and just have a couple of questions. The function returns a diamond of n lines made from asterisks.

  1. Is that a concatenated for loop? Is that a thing you can do?
  2. What is going on in that f-string? How does '':*<{line*2+1} work?
def diamond(n):
    result = ""
    for line in list(range(n)) + list(reversed(range(n-1))):
        result += f"{'': <{n - line - 1}} {'':*<{line*2+1}}\n"

    return result

Solution

  • Regarding the iteration: yes, it iterates over a concatenation of two ranges, but it's not the most optimal way to do it. Using itertools.chain() looks like a better choice.

    For the formatting part: f"{'':*<{n}}" literally means "right-pad the empty string with * to the length of n characters". In other words, it's some cryptic way of saying '*' * n.

    More generally, everything that goes after : defines the format in the format specification mini-language.

    Overall, this is quite a bad piece of code, don't use it as an example.