How to put a half-width space before letters and numbers in Python.

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.

What I want to do this time

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): ...

Postscript

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

How to put a half-width space before letters and numbers in Python.
Display numbers and letters assigned to variables in python print
[Itertools.permutations] How to put permutations in Python
How to get a stacktrace in python
How to use is and == in Python
How to clear tuples in a list (Python)
How to embed a variable in a python string
How to create a JSON file in Python
[Python] How to put any number of standard inputs in a list
To add a module to python put in Julialang
How to notify a Discord channel in Python
[Python] How to draw a histogram in Matplotlib
How to count numbers in a specific range
How to plot autocorrelation and partial autocorrelation in python
How to stop a program in python until a specific date and time
How to convert / restore a string with [] in python
How to run python in virtual space (for MacOS)
[Python] How to expand variables in a character string
[Python] How to sort dict in list and instance in list
How to add page numbers to PDF files (in Python)
How to execute a command using subprocess in Python
[Linux] How to put your IP in a variable
How to develop in Python
[GCF + Python] How to upload Excel to GCS and create a new table in BigQuery
How to slice a block multiple array from a multiple array in Python
How to swap elements in an array in Python, and how to reverse an array.
A story about how to specify a relative path in python.
How to use the __call__ method in a Python class
How to import a file anywhere you like in Python
[Introduction to Udemy Python 3 + Application] 36. How to use In and Not
How to define multiple variables in a python for statement
A standard way to develop and distribute packages in Python
I tried "How to get a method decorated in Python"
How to develop in a virtual environment of Python [Memo]
Comparison of how to use higher-order functions in Python 2 and 3
How to get the last (last) value in a list in Python
How to get a list of built-in exceptions in python
How to write a metaclass that supports both python2 and python3
How to execute external shell scripts and commands in python
Just try to receive a webhook in ngrok and python
How to log in to AtCoder with Python and submit automatically
How to write a Python class
[Python] How to do PCA in Python
How to put a symbolic link
How to use SQLite in Python
[Python] How to delete rows and columns in a table (list of drop method options)
How to use Mysql in python
How to wrap C in Python
How to use ChemSpider in Python
How to use PubChem in Python
How to handle Japanese in Python
How to set a shortcut to switch full-width and half-width with IBus
How to determine the existence of a selenium element in Python
How to install OpenCV on Cloud9 and run it in Python
How to compare lists and retrieve common elements in a list
[Introduction to Python] How to output a character string in a Print statement
How to check the memory size of a variable in Python
[Python] How to add rows and columns to a table (pandas DataFrame)
How to use functions in separate files Perl and Python versions
How to get a string from a command line argument in python
How to create a heatmap with an arbitrary domain in Python