LoginSignup
1
1

競プロ 出力方法まとめ【Python】

Posted at

はじめに

競技プログラミングやプログラミングの練習問題で一番初めにつまづいたのが入出力の方法だったので、今回は出力方法についてまとめました。
入力を受け取る方法についての記事はこちら

基本の関数

print()関数

print() は文字列、数値、bool値、リストなどのオブジェクトを引数として、それを出力する関数である。

a = [1, 2, 3]
print('one')
print(1)
print(True)
print(a)

# one
# 1
# True
# [1, 2, 3]

公式ドキュメント print()より、 print(objects, sep = ' ', end = '\n', file = None, flush = False)
すなわちデフォルトで区切り文字は半角スペース、最後に改行文字が指定されているので、何も指定しない状態でも勝手に空白区切り・改行される。

任意の文字で区切って出力

引数 sep を変更して出力する。

a = 'one'
b = 'two'
c = 'three'
print(a, b, c, sep = ' ! ')

# one ! two ! three

sep に改行文字を指定すると、オブジェクトごとに改行して出力することができる。

a = 'one'
b = 'two'
c = 'three'
print(a, b, c, sep = '\n')

# one
# two
# three

リストを任意の文字で区切って出力

*(リスト名)として print() の引数にすると、リストが展開されて要素が空白区切りで出力される。sep で区切り文字を任意の文字に変更できる。

a = [1, 2, 3]
b = [4, 5, 6]
print(*a)
print(*b, sep = '\n')

# 1 2 3
# 4
# 5
# 6

複数の print() の出力

デフォルトでは end = '\n' なので print() の末尾は改行される。end に任意の文字を指定することで、改行されずに次の出力を続けることができる。

a = 'one'
b = 'two'
c = 'three'
print(a, end = ' ! ')
print(b, end = ' ? ')
print(c)

# one ! two ? three

空行の出力

デフォルトで end = '\n' が指定されているので、 print() のみで空行が出力できる。

print()

#

数値と文字列を合わせて出力

型が違うと出力できないので、数値を str() を用いて文字列にする。

a = 'one'
b = 1
print(a + ' is ' + str(b))

# one is 1

文字列の中に変数を埋め込んで出力

f 文字列(フォーマット文字列)にすると、型を変えずに、変数を埋め込むことができる。

a = 'one'
b = 1
print(f'{a} is {b}')

# one is 1
1
1
0

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
1