Pythonの基礎 - 基本的なデータ型
概要
ここでは、Pythonプログラミングの基礎として、基本的な文法等を記載する。
print関数
以下のように、文字列リテラルをprint関数で出力するには()の中にダブルクォーテーション""で文字列を囲んで入力する。
ダブルクォーテーションの代わりにシングルクォーテーションで囲んでもよい。
<syntaxhighlight lang="python"> print("Python") # 出力 python </source>
次に、以下のように入力すると、Python PHPと出力される。
<syntaxhighlight lang="python"> print("Python", "PHP") # 出力 Python PHP </source>
print関数のオプション
sepオプション
上記のように、複数の引数を並べて入力すると、文字列の間に半角の空白文字が1つ入る。
例えば、Python,PHPのように、間にカンマを入れて出力する場合は、sepオプションを使用する。
<syntaxhighlight lang="python"> print("Python", "PHP", sep=",") # 出力 Pyhon,PHP </source>
endオプション
endオプションは、文末の処理を行う時に使用する。通常は、標準で改行コード(\n)が設定されている。
明示的に入力すると以下のようになる。
<syntaxhighlight lang="python"> print("Python", "PHP", sep=",", end="\n") # 出力 Python,PHP </source>
次に、以下のように、endオプションを空にして実行すると、Python,PHPPython,PHPと改行されずに繋がって表示される。
これは、1行目は改行しないという意味になる。
<syntaxhighlight lang="python"> print("Python", "PHP", sep=",", end="") print("Python", "PHP", sep=",", end="\n") # 出力 Python,PHPPython,PHP </source>
また、endオプションには以下のような使い方もある。
最後の改行にエクスクラメーション(!)を入れて出力する場合は、end="!\n"のように入力する。
<syntaxhighlight lang="python"> print("Python", "PHP", sep=",", end="!\n") # 出力 Python,PHP! </source>
変数の宣言と使用
基本
<syntaxhighlight lang="python"> msg = "こんにちは、Python" num = 100 print(msg) print(num) # 出力 こんにちは、Python 100 </source>
次にように、文字列リテラルを代入した変数msgに、数値リテラルを代入する場合、変数msgは自動的に整数型と認識される。
<syntaxhighlight lang="python"> msg = "こんにちは、Python" num = 100 msg = num print(msg) # 出力 100 </source>
Pythonでは、変数を宣言する時、データ型を自動的に認識するので型宣言は不要である。(これを動的型付けと呼ぶ)
ただし、型宣言があると理解しやすい時もあるので、以下のように、変数の型も併せて記述する方法もある。
<syntaxhighlight lang="python"> msg: str = "こんにちは、Python" num: int = 100 print(msg) print(num) </source>
変数の型を知りたい場合、type関数を使用してデータ型を表示させることができる。
<syntaxhighlight lang="python"> msg = "こんにちは、Python" num = 100 print(msg, type(msg)) print(num, type(num)) # 出力 こんにちは、Python <class 'str'> 100 <class 'int'> </source>
型変換(キャスト)
文字列型の変数strnumを整数型の変数inumに代入する場合、以下のように型変換を行うと、整数型の100として表示される。
ただし、数値ではない文字列を数値型に変換することはできない。
<syntaxhighlight lang="python"> strnum = "100" inum = int(strnum) print(inum, type(inum)) # 出力 100 <class 'int'> </source>
数値と四則演算
Pythonの数値型には、整数型(int)と浮動小数点数型(float)がある。
Pythonでは、他のプログラム言語にあるようなインクリメント(++)やデクリメント(--)は使用できない。
文字列
Pythonでの文字列の特徴として、文字を順番に並べて文字列として扱っている。
文字列には、先頭の文字から順番に0から始まるインデックスが振られていて、これを指定することで文字列を操作することができる。
例えば、"Python"という文字列では、"P"のインデックスが0、"y"のインデックスが1、というインデックスが振られている。
このように、文字列は順序を持つ型なのでシーケンス型のひとつになっている。
<syntaxhighlight lang="python"> print('Hello') print("Hello") type("Hello") print("Hello!" * 3) greeting = "Hello " + "Python!" print(greeting) len(greeting) # 出力 Hello Hello <class 'str'> Hello!Hello!Hello! Hello Python! 13 </source>
改行
改行する箇所に、\nを入れる。
<syntaxhighlight lang="python"> print("Hello, \nPython") # 出力 Hello, Python </source>
複数行にわたる長い文章の表示は、トリプルクォート(""" """)で囲む。
トリプルクォートで囲んだ部分は、改行も自由にできる。
<syntaxhighlight lang="python"> strhoge = """Hello, Python""" print(strhoge) # 出力 Hello, Python </source>
文字列が長くなって読みにくい場合は、丸括弧()の中で改行する文字列ごとにダブルクォーテーションで囲むか、
改行する場所でバックスラッシュ\を入れることでコードを途中で改行して見やすくすることができる。
<syntaxhighlight lang="python"> str1 = ("Hello, " "Python") str2 = "Hello, "\ "Python" </source>
文字列の抽出と分割
文字列は先頭の文字のインデックスを0として順番にインデックスが割り当てられている。
例えば、文字列pythonにインデックスを振ると次のようになる。
p | y | t | h | o | n |
---|---|---|---|---|---|
0 | 1 | 2 | 3 | 4 | 5 |
-6 | -5 | -4 | -3 | -2 | -1 |
文字の抽出
インデックスを使用して、文字列の中から文字を抽出する。 文字列型の変数の後ろに[]を使用して、その中にインデックスを指定する。 例えば、以下のように、変数wordの後ろに[]をつけて抽出する文字列のインデックスを指定する。
<syntaxhighlight lang="python"> word = "python" print(word[0]) print(word[1]) print(word[-1]) print(word[-2]) # 出力 p y n o </source>
文字列の抽出
文字列を抽出する場合は、コロンを使用して分割する範囲を指定する。
startの位置に抽出する文字の先頭のインデックスを指定し、endの位置にend - 1番目のインデックスを指定する。stepは、その文字数毎に抜き出すという意味になる。
[start:end:step]
<syntaxhighlight lang="python"> word = "python" print(word[0:3]) print(word[:3]) print(word[2:5]) print(word[2:]) print(word[-2:]) print(word[-4:-2]) words = "abcdefghijklmnopqrstuvwxyz" print(words[::6]) print(words[2:21:4]) # 出力 pyt pyt tho thon on th agmsy cgkos </source>
文字列の検索・置換・結合
len関数で文字列の長さを出力
<syntaxhighlight lang="python"> s = "I am playing with Python. It is not a serpent Python." print(len(s)) # 出力 53 </source>
in演算子を使用して存在の有無を調べる
文字列の中に、特定の文字や文字列が含まれるかどうかをin演算子を使用して調べる。
<syntaxhighlight lang="python"> s = "I am playing with Python. It is not a serpent Python." in_python_word = "Python" in s in_php_word = "PHP" in s print(in_python_word) print(in_php_word) # 出力 True False </source>
split関数で文字列を分割する
split関数を引数なしで使用すると、セパレータとして空白文字(スペース区切り)が設定される。
出力には、それぞれの単語ごとに分割されて、角括弧[]の中(リスト形式の表現)に入れられる。
<syntaxhighlight lang="python"> s = "I am playing with Python. It is not a serpent Python." print(s.split()) # 出力 ['I', 'am', 'playing', 'with', 'Python.', 'It', 'is', 'not', 'a', 'serpent', 'Python.'] </source>
次に、セパレータにピリオドを指定して分割する。
<syntaxhighlight lang="python"> s = "I am playing with Python. It is not a serpent Python." print(s.split(".")) # 出力 ['I am playing with Python'. ' It is not a serpent Python'] </source>
更に、セパレータにtを指定して分割する。
<syntaxhighlight lang="python"> s = "I am playing with Python. It is not a serpent Python." print(s.split("t")) # 出力 ['I am playing wi', 'h Py', 'hon. I', ' is no', ' a serpen', ' Py', 'hon'] </source>
join関数で結合する
join関数は、split関数とは逆の関数で、文字列のリストを1つの文字列に結合する。
<syntaxhighlight lang="python"> s = ['I am playing wi', 'h Py', 'hon. I', ' is no', ' a serpen', ' Py', 'hon.'] t = "t" print(t.join(s)) # 出力 I am playing with Python. It is not a serpent Python. </source>
find関数で検索する
find関数は、対象の文字列から検索したい文字列がどこにあるのか調べる関数である。
以下の例では、Pythonという文字列が先頭から数えて18番目のインデックスにあるという意味になる。
<syntaxhighlight lang="python"> s = "I am playing with Python. It is not a serpent Python." print(s.find("Python")) # 出力 18 </source>
また、文字列を後ろから検索する場合は、rfind関数を使用する。
<syntaxhighlight lang="python"> s = "I am playing with Python. It is not a serpent Python." print(s.rfind("Python")) # 出力 46 </source>
count関数で数える
len関数は全体の個数を数えることができるが、文字列の中に特定の文字列を数えるにはcount関数を使用する。
<syntaxhighlight lang="python"> s = "I am playing with Python. It is not a serpent Python." print(s.count("Python")) print(s.count("n")) # 出力 2 5 </source>
replace関数で置換する
文字や文字列を置き換える場合は、replace関数を使用する。
<syntaxhighlight lang="python"> s = "I am playing with Python." print(s.replace("Python", "Swift")) # 出力 I am playing with Swift. </source>
capitalize関数、title関数、upper関数、lower関数で文字列を変換する
これらの関数は、文字列の大文字・小文字を操作する時に使用する。
- capitalize()は先頭の単語をタイトルケースに変換する。
- title()は全ての単語をタイトルケースに変換する。
- upper()は全ての文字を大文字に変換する。
- lower()は全ての文字を小文字に変換する。
<syntaxhighlight lang="python"> s = "I am playing with Python. It is not a serpent Python." print(s.capitalize()) print(s.title()) print(s.upper()) print(s.lower()) # 出力 I am playing with python. it is not a serpent python. I Am Playing With Python. It Is Not A Serpent Python. I AM PLAYING WITH PYTHON. IT IS NOT A SERPENT PYTHON. i am playing with python. it is not a serpent python. </source>