Hello, this is ricky. I didn't know how to write a half-width space before the character string, so I'll look it up and keep it as a memorandum. I wasn't used to format (), so it was a good practice.
I want to display numbers with one half-width space.
How to write
sample.py
num = 1
width = 2
print("{num:>{width}}".format(num=num, width=width))
Output: 1 I have a half-width space properly.
You can also write something like this.
another_sample.py
num = "a"
width = 2
print("{num:*>{width}}".format(num=num, width=width))
Output: * a You can change it to characters or change the half-width space to *.
Commentary Express by writing width in the second argument of format. Since this width is the length including numbers, 2 which is more than the number of digits is declared in width. Apparently, it seems to display the length of the half-width space including numerical values.
Official document excerpt
str.format(*args, **kwargs) Performs a string formatting operation. The string that calls this method contains regular characters or replacement fields separated by {}. Each replacement field contains the index number of the positional argument or the name of the keyword argument. The return value is a copy of the string where each replacement field is replaced with the string value of the corresponding argument.
Excerpt from the official document glossary
parameter (Dummy argument) A named entity that specifies the actual argument that the function receives in the definition of the function (or method). There are five types of formal parameters: Position or Keyword: Specifies an argument that can be passed by position or as a keyword argument. This is the default formal argument type, for example foo and bar below: def func(foo, bar=None): ...
I will add it because @shiracamus taught me another way to write it.
postscript.py
num = 1
width = 2
print(f"{num:>{width}}")
This is easier to see. You should be aware that f is format f.
@shiracamus Thank you for letting me know.
For reference, I will quote the format part of url of PEP8.
Format specifiers Format specifiers may also contain evaluated expressions. This allows code such as:
width = 10 precision = 4 value = decimal.Decimal('12.34567') f'result: {value:{width}.{precision}}' 'result: 12.35' Once expressions in a format specifier are evaluated (if necessary), format specifiers are not interpreted by the f-string evaluator. Just as in str.format(), they are merely passed in to the format() method of the object being formatted.
Summary I only wrote the keyword argument in the documentation, so I decided to investigate it myself. I didn't understand the keyword arguments so much that I wasted time. It seems that we can make a good space in the future.
Recommended Posts