Search code examples
pythonf-string

Is it possible to use whitespace in format specifier


If I have following print statements:

print("#"*80)
print(f"##{'':.^76}##")
print(f"##{'Hello World':.^76}##")
print(f"##{'':.^76}##")
print("#"*80)

I will get a nice border around my "Hello World" but with dots:

################################################################################
##............................................................................##
##................................Hello World.................................##
##............................................................................##
################################################################################

If I use a ' ' instead of the . in the second to fourth print statement, I will get a ValueError: Invalid format specifier.

How can replace the dot with whitespace or any other ascii symbol?


Solution

  • Isn't it enough to simply remove the dot and leave a space?

    So:

    print("#"*80)
    print(f"##{'': ^76}##")
    print(f"##{'Hello World': ^76}##")
    print(f"##{'': ^76}##")
    print("#"*80)
    

    output will be:

    ################################################################################
    ##                                                                            ##
    ##                                Hello World                                 ##
    ##                                                                            ##
    ################################################################################