2
4

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()のメモ

Posted at

これは初心者が書いたメモ
#そのまま出力

print("Hello World")
print('Hello World')
print(1)
出力結果
Hello World
Hello World
1

文字列はダブルクォーテーションかシングルクォーテーションでくくって()の中に入れる。
数値はそのまま()の中に入れる。

#変数に入れてから出力

hoge1="Hello"
hoge2="World"
moge1=1
moge2=2
print(hoge1)
print(moge1)
出力結果
Hello
1

変数を()の中に入れる。

#文字列の結合

print(hoge1+hoge2)
print(moge1+moge2)
#print(hoge1+moge1)#これはエラー
出力結果
HelloWorld
3

2行目は数値なので結合にはならず足し算の結果が出力される。
文字列と数値の結合は出来ないので3行目はエラーが出る。

#並べて出力

print(hoge1,hoge2)
print(moge1,moge2)
print(hoge1,moge1)#これはエラーにならない
出力結果
Hello World
1 2
Hello 1

間が半角スペースで区切られて出力される。

#区切りを指定

print(hoge1,hoge2,sep=",")
print(hoge1,hoge2,sep="")
出力結果
Hello,World
HelloWorld

sep=","でコンマを指定。半角スペースだった区切りがコンマになる。デフォルトではsepの値が半角スペースになっているのを変更しているということ。
sep=""にすると結合した時と結果は同じになる。

#末尾を指定して改行させたりさせなかったり

print(hoge1)
print(hoge2)
出力結果
Hello
World

こう書くと改行されて出力される。

print(hoge1,end=",")
print(hoge2)
出力結果
Hello,World

end=","でコンマを指定。末尾にコンマを付け足して改行しない。デフォルトではendの値が改行コードになっているのを変更しているということ。

print(hoge1,end=",\n")
print(hoge2)
出力結果
Hello,
World

だからこうすると末尾にコンマを付け足して改行する。

print(hoge1,end="")
print(hoge2)
出力結果
HelloWorld

これはただ単に改行しないし何も付け足さない。

#逆に1行で改行したい場合

print("Hello\nWorld")
出力結果
Hello
World

間に改行コードの\nを入れる。

print(hoge1+"\n"+hoge2)
print(hoge1,"\n",hoge2,sep="")

変数を使うならこう。

#公式
Python 3.7.3 ドキュメント

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?