LoginSignup
0
4

More than 3 years have passed since last update.

Pythonのstr.formatを存分に使う

Last updated at Posted at 2020-08-10

freeCodeCampでコツコツPythonを勉強しています。

前回の記事ではTime Calculatorに挑戦しました、今回はBudget Appに挑戦します。

  • Python for Everybody
  • Scientific Computing with Python Projects
    • Arithmetic Formatter
    • Time Calculator
    • Budget App(今回はここ)
    • Polygon Area Calculator
    • Probability Calculator

3問目:Budget App

求められてることは以下の通り

  • Categoryクラスの作成
    • depositメソッド: 預ける
    • withdrawメソッド: 引き出す
    • transferメソッド: 送金
    • get_balanceメソッド: 残高表示
    • check_fundsメソッド: そのお金を引き出せるかチェック
    • strメソッド: 以下のような表示
*************Food*************
initial deposit        1000.00
groceries               -10.15
restaurant and more foo -15.89
Transfer to Clothing    -50.00
Total: 923.96
  • create_spend_chartメソッド: 以下のような表示
Percentage spent by category
100|          
 90|          
 80|          
 70|          
 60| o        
 50| o        
 40| o        
 30| o        
 20| o  o     
 10| o  o  o  
  0| o  o  o  
    ----------
     F  C  A  
     o  l  u  
     o  o  t  
     d  t  o  
        h     
        i     
        n     
        g    

個人的ポイント: formatでの書式指定

Categoryクラスのstrメソッドやcreate_spend_chartメソッドでいい感じに書式を揃えるためにstr.formatメソッドを存分に使うことが必要。

様々な書式指定

  • インデックス番号
    • '{0} {1} {0}'.format('バナナ', 'りんご')
    • -> バナナ りんご バナナ
  • 文字寄せ・パディング
    • 右寄せ: '{:>20}'.format('test')
    • -> '○○○○○○○○○○○○○○○○test'
    • 左寄せ: '{:<20}'.format('test')
    • -> 'test○○○○○○○○○○○○○○○○'
    • 中央寄せ: '{:^20}'.format('test')
    • -> '○○○○○○○○test○○○○○○○○'
    • 空白をなんらかの文字で埋めたい場合: '{:->20}'.format('test')
    • -> '----------------test'
    • ゼロパディング: '{:010d}'.format(100)
    • -> '0000000100'
  • 小数点以下の桁数指定
    • '{:.2f}'.format(1.234567)
    • -> '1.23'

Categoryメソッドのstrメソッドの実装

*************Food*************  <- ヘッダー
initial deposit        1000.00 -|
groceries               -10.15  |- ボディ
restaurant and more foo -15.89  |
Transfer to Clothing    -50.00 -|
Total: 923.96                   <- トータル

ヘッダー、ボディ、トータルの3つの部分に分割して考えてみる。
条件は以下の通り

  • ヘッダーは30文字
  • ボディの左側の説明は最大23文字、右側の金額は最大7文字で少数第2位まで表示
category_name = 'Food'
ledger = [...] # 金額と説明を持ったオブジェクトのリスト

def __str__(self):
    header = '{:*^30}'.format(category_name)
    body = ['{:<23}{:>7.2f}'.format(item.description, item.amount) for item in ledger]
    total = sum([item.amount for item in ledger])

    return header + '\n' + '\n'.join(body) + '\n' + 'Total: {}'.format(total)

最後に

普段はコンソール出力でビジュアライズすることがあまりないので新鮮でした。
是非、create_spend_chartメソッドにチャレンジしてみてください。

次の問題はPolygon Area Calculatorです。

0
4
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
0
4