0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Pythonで文字、数字の前に半角スペースを入れる方法。

Last updated at Posted at 2020-10-15

こんにちは、rickyです。
文字列の前に半角スペースを書く書き方がわからなかったので調べて備忘録としておきます。
format()は使い慣れていなかったのでいい練習になりました。

今回やりたいこと

 数字を半角スペースを1つおいて表示をしたい。

書き方

sample.py
num = 1
width = 2

print("{num:>{width}}".format(num=num, width=width))

出力: 1
ちゃんと半角スペースをおけました。

こんなものも書ける。

another_sample.py
num = "a"
width = 2

print("{num:*>{width}}".format(num=num, width=width))

出力:a
文字に変えたり、半角スペースを
に変えることもできる。

解説
formatの第二引数にwidthを書いて表現する。
このwidthは数字込みの長さになるので桁数より多い2をwidthに宣言している。
どうやら数値込みで半角スペースの長さを表示しているようです。

公式ドキュメント抜粋

str.format(*args, **kwargs)
文字列の書式化操作を行います。このメソッドを呼び出す文字列は通常の文字、または、 {} で区切られた置換フィールドを含みます。それぞれの置換フィールドは位置引数のインデックスナンバー、または、キーワード引数の名前を含みます。返り値は、それぞれの置換フィールドが対応する引数の文字列値で置換された文字列のコピーです。

公式ドキュメント用語集より抜粋

parameter
(仮引数) 名前付の実体で 関数 (や メソッド ) の定義において関数が受ける 実引数 を指定します。仮引数には5種類あります:
位置またはキーワード: 位置 でまたは キーワード引数 として渡すことができる引数を指定します。これはたとえば以下の foo や bar のように、デフォルトの仮引数の種類です:
def func(foo, bar=None): ...

追記

@shiracamus様より別の書き方を教えていただいたので追記します。

postscript.py
num = 1
width = 2

print(f"{num:>{width}}")

こちらの方が見やすいです。
fはformatのfだということに気を付けておけばよさそうです。

@shiracamus様教えていただきありがとうございます。

参考資料としてPEP8のurlのformatの箇所を引用します。

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.


まとめ
ドキュメントにキーワード引数としか書いていなかったので、自分で調査することになった。
キーワード引数についての理解が浅かったので無駄な時間を取られてしまった。
今後はうまくスペースを作ることができそう。

0
0
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?