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 1 year has passed since last update.

(D⇒C)大きな数値を 3 けたごとにカンマ区切りで出力

Last updated at Posted at 2023-11-10

今日はPythonでこの問題
https://paiza.jp/works/mondai/stdout_primer/stdout_primer__specific_split_step6

・出力された数値を3桁ごとにカンマ区切りするというやつ
・実はPythonには便利な関数があるが、それを使わずこれまで使ったループとrange関数と新しくでてきたlen関数で作成
 (便利な関数は後ほど)

input_line = input();
for i in range(len(input_line)):
    if i % 3 == 0 and i != 0:
        print(",",end="")
    print(input_line[i],end="")

・LEN関数で全体の桁数を調べそれでループさせる
print()関数をうまく活用する
3桁ごとにカンマということは、つまり3回目は3で割り切れ、また0ではないときにコンマをプリントさせればOKということ(この考え方は重要)

★もう1つの解法
・format関数で引数にコンマを使うと3桁ごとのカンマ区切りが出力される

input_line = int(input());
print(format(input_line,','))

★(2023.11.11追記)
コメントよりf-stringなる書き方もあるようです。
コメントありがとうございます!
私の方でも調べてみました。
https://realpython.com/python-f-strings/#:~:text=Also%20called%20formatted%20string%20literals,expressions%20enclosed%20in%20curly%20braces.

ただし、必ず数値型でないとだめなのがポイントです。
なのでinput()のあとに数値型に変更しないとf-stringが使えません

input_line = int(input());
print(f'{input_line:,}')
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?