Skip to content
Advertisement

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?

Advertisement

Answer

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                                 ##
##                                                                            ##
################################################################################
Advertisement