1
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 5 years have passed since last update.

Pythonのprintで%dや%sを使う方法やformatメソッドについてもメモ書き

Last updated at Posted at 2019-07-19

はじめに

しがない地方大学院生をしています、Sotaです。
プログラミング初心者のため、内容に誤りがあるかもしれません。
もし、誤りがあれば修正するので、どんどん指摘してください。

自分はC言語からプログラミングを勉強したので、%dや%fの表現に慣れています。
そのため、桁数指定などで、ストレスを感じたので、Pythonでも%dや%fを使える表現をメモします。

Pythonで%dや%sを使う

Pythonでprintf関数のような表現を使うには、
'文字列' % 変数 とすれば記述できます。
(例)

y = 10000
d = 100

print('100$は%d円' % y) #100$は10000万円
print('%d円は%d$' % (y, d)) #10000万円は100$

このような感じです。
もちろん文字列やfloat、桁数指定%.2fなども可能です。

formatメソッド

文字列メソッドformat()でも似たような書き方ができます。
文字列中に置換フィールド{}が指定した引数と対応して置換されます。
文字列.format(変数)と書きます。
(例)

y = 10000
d = 100

print('100$は{}万円'.format(y)) #100$は10000万円
print('{}万円は{}$'.format(y, d)) #10000万円は100$
1
0
2

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
1
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?