【入門 Python】変数、数値、文字列
はじめに
この記事では主に、株式会社オライリー・ジャパンの「入門 Python3」を中心に学んだことを備忘録目的でまとめていきます。参考書籍と必ずしもセクションが同じとは限りませんので、あらかじめご承知おきください。基本的に知識まとめの文章表現は常体(だ・である調)で表現しています。
参考書籍について
より詳しく内容を知りたい方は「入門 Python3」ををお手に取ってみてください。なお、最新版(第2版)はこちら。
Pythonの実行環境について
この記事ではPython付属の対話型インタープリタを用いることとします。起動方法はシェル(windows:コマンドプロンプト, Mac:zshなど)に次のように入力すると起動できます。
# Pythonと入力すると対話型インタープリタが起動
C:\Users\user>Python
Python 3.11.1 (tags/v3.11.1:a7a450f, Dec 6 2022, 19:58:39) [MSC v.1934 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
なお、対話型インタープリタの修了方法はquit()
を入力すると終了します。
>>> quit()
C:\Users\user>
1. 変数
変数名として使えるのは次の文字のみ。
- 小文字の英字(a~z)
- 大文字の英字(A~Z)
- 数字(0~9)
- アンダースコア(_)
1.1. 変数は値の参照をしている
Pythonの変数は名前を付けるだけであり、値をコピーしているわけではない。つまり変数は値の参照を行っている。
>>> a = 7
>>> print(a)
7
Javaと比較
Pythonに対してJavaでは、基本型変数は値として数値(または文字)そのものを保持し、参照型変数は値としてオブジェクトの位置情報を指し示すものを保持する。
- Javaの基本型変数:byte型、short型、int型、long型、float型、double型、char型、boolean型
- Javaの参照型変数:クラス、配列、インターフェースなどを含む基本型以外の方すべて
public static void main(String[] args){
int a = 100;
int b = 100;
System.out.println(a == b); // true
String c = "aiueo";
String d = "aiueo";
System.out.println(c == d); // false
System.out.println(c.equals(d)); // true
}
1.2. 数字は先頭に使えない
数字は変数名の先頭としては使えない。
>>> 1a = 7
File "<stdin>", line 1
1a = 7
^
SyntaxError: invalid decimal literal
2. 数値
Pythonには、整数と浮動小数点のサポートがされている。
2.1. 整数
Pythonの数字の並びは、リテラル(べた書き)の整数とみなされる。これをリテラル整数といったりもする。
※リテラルの「べた書き」の意味合いは、「分かりそう」で「分からない」でも「分かった」気になれるIT用語辞典を参考にしました。複数の文献なども読んだのですが、現時点で一番しっくり来ているため、現状はこちらを採用しました。
>>> 0
0
>>> 1
1
>>> +2
2
>>> -3
-3
数字の先頭に0
を置くと例外が発生する。
>>> 04
File "<stdin>", line 1
04
^
SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers
「10 進整数リテラルの先頭のゼロは許可されません。 8 進整数には 0o 接頭辞を使用してください。」とエラー文が表示された。
2.2. 浮動小数点数
浮動小数点数は小数点以下の値を持ち、整数と同じように算術演算子やdivmod()
関数を使うことができる。
>>> 123.4
123.4
2.3. 算術演算子
2.3.1. 加算
>>> 1 + 2
3
リテラル整数と整数値が代入された変数を汲みわせることもできる。
>>> a = 1
>>> a + 2
3
+
と=
を組み合わせることもできる。次の演算は、a = a + 1
と同じ意味である。
>>> a = 1
>>> a += 1
>>> a
2
2.3.2. 減算
>>> 2 - 1
1
>>> 1 - 2
-1
リテラル整数と整数値が代入された変数を汲みわせることもできる。
>>> a = 2
>>> a - 1
1
-
と=
を組み合わせることもできる。次の演算は、a = a - 1
と同じ意味である。
>>> a = 2
>>> a -= 1
>>> a
1
2.3.3. 乗算
>>> 2 * 3
6
>>> 2 * (-3)
-6
>>> (-2) * (-3)
6
リテラル整数と整数値が代入された変数を汲みわせることもできる。
>>> a = 2
>>> a * 3
6
*
と=
を組み合わせることもできる。次の演算は、a = a * 3
と同じ意味である。
>>> a = 2
>>> a *= 3
>>> a
6
2.3.4. 浮動小数点数の除算
/
は除算を行う算術演算子で、計算結果は浮動小数点数で返される。
>>> 4 / 3
1.3333333333333333
>>> 4 / 2
2.0
リテラル整数と整数値が代入された変数を汲みわせることもできる。
>>> a = 4
>>> a / 3
1.3333333333333333
/
と=
を組み合わせることもできる。次の演算は、a = a / 3
と同じ意味である。
>>> a = 4
>>> a /= 3
>>> a
1.3333333333333333
2.3.5. 整数の除算(切り捨て)
//
も除算を行う算術演算子だが、計算結果は剰余を捨てた整数で返される。
>>> 4 // 3
1
>>> 4 // 2
2
リテラル整数と整数値が代入された変数を汲みわせることもできる。
>>> a = 4
>>> a // 3
1
//
と=
を組み合わせることもできる。次の演算は、a = a // 3
と同じ意味である。
>>> a = 4
>>> a //= 3
>>> a
1
2.3.6. 剰余
%
は複数の用途があるが、算術演算子としては剰余を返す。
>>> 5 % 3
2
>>> 4 % 2
0
リテラル整数と整数値が代入された変数を汲みわせることもできる。
>>> a = 5
>>> a % 3
2
%
と=
を組み合わせることもできる。次の演算は、a = a % 3
と同じ意味である。
>>> a = 5
>>> a %= 3
>>> a
2
divmod()関数
divmod()
関数を用いると、商と剰余をタプルで返す。
>>> divmod(5, 3)
(1, 2)
2.3.7. 指数
**
は指数の演算結果を返す。
# 2の3乗
>>> 2 ** 3
8
# -2の3乗
>>> -2 ** 3
-8
リテラル整数と整数値が代入された変数を汲みわせることもできる。
>>> a = 5
>>> a % 3
2
**
と=
を組み合わせることもできる。次の演算は、a = a ** 3
と同じ意味である。
>>> a = 2
>>> a **= 3
>>> a
8
2.2. 基数
整数はプレフィックス(接頭辞)を指定しない場合は10進数(基数10)と解釈される。Pythonでは10進数のほかに3種類の基数を使ってリテラル整数を表すことができる。
- 2進数:
0b
または0B
- 8進数:
0o
または0O
- 16進数:
0x
または0X
# 10進数
>>> 10
10
# 2進数
>>> 0b10
2 # 10進数では2
# 8進数
>>> 0o10
8 # 10進数では8
# 16進数
>>> 0x10
16 # 16進数では16
2.3. 型の変換
2.3.1. 整数
bool値はTrueは1に、Falseは0に変換される。
>>> import math
>>> int(True)
1
>>> int(False)
0
浮動小数点数を整数に変換すると、小数点以下の部分が切り捨てられる。
>>> import math
>>> int(12.3)
12
整数に変換できる文字列を引数に取ると、文字列ではなく整数に変換される。
>>> import math
>>> int('123')
123
>>> int('-123')
-123
2.3.2. 浮動小数点
bool値はTrueは1.0に、Falseは0.0に変換される。
>>> import math
>>> float(True)
1.0
>>> float(False)
0.0
整数も小数点表示になる。
>>> import math
>>> float(123)
123.0
浮動小数点数に変換できる文字列を引数に取ると、文字列ではなく浮動小数点数に変換される。
>>> import math
>>> float('123')
123.0
2.4. 数学関数
Pythonの標準ライブラリにmathがあり、これにより一般的な数学関数や定数が備わっている。以下にいくつか例を挙げる。
2.4.1. 定数
2.4.1.1. 円周率
>>> import math
>>> math.pi
3.141592653589793
2.4.1.2. ネイピア数
>>> import math
>>> math.e
2.718281828459045
2.4.2. 三角関数
2.4.2.1. 正弦
引数はラジアンである。つまりmath.pi / 2
を入れる。
>>> import math
>>> math.sin(math.pi / 2)
1.0
2.4.2.2. 余弦
>>> import math
>>> math.cos(math.pi)
-1.0
2.4.2.3. 正接
>>> import math
>>> math.tan(math.pi / 4)
0.9999999999999999
2.4.3. 指数関数
>>> import math
>>> math.exp(1)
2.718281828459045
>>> import math
>>> math.exp2(3)
8.0
2.4.4. 対数関数
>>> import math
>>> math.log(math.e)
1.0
>>> import math
>>> x = 2
>>> math.log2(x)
1.0
2.4.5. その他の数学関数
2.4.5.1. 順列の関数
>>> import math
>>> n = 5
>>> k = 2
>>> math.perm(n, k)
20
2.4.5.2. 階乗の関数
階乗
>>> import math
>>> math.factorial(3)
6
2.4.5.3. 組み合わせの関数
>>> import math
>>> n = 3
>>> k = 1
>>> math.comb(n, k)
3
2.4.5.4. 最小公倍数の関数
自然数
>>> import math
>>> m = 3
>>> n = 5
>>> math.lcm(m, n)
15
2.4.5.5. 最大公約数の関数
自然数
>>> import math
>>> m = 12
>>> n = 4
>>> math.gcd(m, n)
4
3. 文字列
3.1. クォートを使った作成
Pythonの文字列は、シングルクォートまたはダブルクォートで文字を囲んで作る。
# 十人十色
>>> 'So many men, so many minds.'
'So many men, so many minds.'
# ローマは一日にしてならず
>>> "Rome wasn't built in a day."
"Rome wasn't built in a day."
トリプルクォートでも文字列は作れるが、これは複数行文字列を作る際によく用いる。
>>> famous_quote = '''Would you like me to give a formula for success?
... It\'s quite simple, really: Double your rate of failure.
... You are thinking of failure as the enemy of success.
... But it isn\'t at all.
... You can be discouraged by failure or you can learn from it,
... so go ahead.(Thomas J. Watson)'''
なお、print()関数の出力結果と、対話型インタープリタの自動エコーの出力では以下の違いがある。
# print()関数
>>> print(famous_quote)
Would you like me to give a formula for success?
It's quite simple, really: Double your rate of failure.
You are thinking of failure as the enemy of success.
But it isn't at all.
You can be discouraged by failure or you can learn from it,
so go ahead.(Thomas J. Watson)
# 対話型インタープリタの自動エコー
>>> famous_quote
"Would you like me to give a formula for success?\nIt's quite simple, really: Double your rate of failure.\nYou are thinking of failure as the enemy of success.\nBut it isn't at all.\nYou can be discouraged by failure or you can learn from it,\nso go ahead.(Thomas J. Watson)"
3.2. str()を使った型変換
str()関数で他のデータ型を文字列(str型)に変換できる。
# float型→str型
>>> type(12.3)
<class 'float'>
>>> str(12.3)
'12.3'
>>> type(str(12.3))
<class 'str'>
# bool型→str型
>>> type(True)
<class 'bool'>
>>> str(True)
'True'
>>> type(str(True))
<class 'str'>
3.3. エスケープシーケンス
エスケープシーケンスとは、「通常の文字列では表せない特殊な文字や機能を、規定された特別な文字の並びにより表したもの。」(ウィキペディアより)
代表的なエスケープシーケンスを以下に挙げる。なお、文字列を囲むために使っているシングル(ダブル)クォートを文字列内でもリテラルとして使う場合は\'
、\"
と表記する。
\n
3.3.1. 改行>>> text = 'line1 \nline2 \nline3'
>>> print(text)
line1
line2
line3
\t
3.3.2. タブ>>> print('\tcol1 \t col2 \tcol3')
col1 col2 col3
>>> print('row1 \t1 \t2 \t3')
row1 1 2 3
>>> print('row2 \t1 \t2 \t3')
row2 1 2 3
3.4. +による連結
+演算子を使えばリテラル文字列、文字列変数を連結することができる。
# 遅れても、やらないよりはまし。+ いつでも夜明け前が一番暗い。
>>> "Better late than never." + "It\'s always darkest before the dawn."
"Better late than never.It's always darkest before the dawn."
``
リテラル文字列の場合は、順に並べるだけでも連結できる。
```sh
>>> "Better late than never." "It\'s always darkest before the dawn."
"Better late than never.It's always darkest before the dawn."
print()関数は引数の文字列の間に自動的にスペースを挿入し、末尾に改行を追加する。
>>> a = "Better late than never."
>>> b = "It\'s always darkest before the dawn."
>>> print(a, b)
Better late than never. It's always darkest before the dawn.
3.5. *による繰り返し
*
演算子は文字列を繰り返すことができる。
>>> a = '-' * 40 + '\n'
>>> b = 'The first step is always the hardest.' + '\n'
>>> print(a + b + a)
----------------------------------------
The first step is always the hardest.
----------------------------------------
3.6. 文字の抽出:[]
文字列の中の文字を一つ取り出すときは、変数名の後ろに[]
で囲んだ文字のオフセットを書く。
>>> letters = 'abcdefghijklmnopqrstuvwxyz'
>>> letters[0]
'a'
>>> letters[5]
'f'
>>> letters[-5]
'v'
3.7. スライス:[start:end:step]
文字列の中から部分文字列を取り出すときは、スライス[先頭オフセット(start):末尾オフセット(end):ステップ(step)]を用いる。
# [:]は、先頭から末尾までのシーケンス全体を抽出する
>>> letters = 'abcdefghijklmnopqrstuvwxyz'
>>> letters[:]
'abcdefghijklmnopqrstuvwxyz'
# [start:]は、startオフセットから末尾までのシーケンスを抽出する
>>> letters = 'abcdefghijklmnopqrstuvwxyz'
>>> letters[5:]
'fghijklmnopqrstuvwxyz'
# [:end]は、先頭からend-1オフセットまでのシーケンスを抽出する
>>> letters = 'abcdefghijklmnopqrstuvwxyz'
>>> letters[:5]
'abcde'
# [start:emd]は、startオフセットからend-1オフセットまでのシーケンスを抽出する
>>> letters = 'abcdefghijklmnopqrstuvwxyz'
>>> letters[5:10]
'fghij'
# [start:end:step]は、step文字ごとにstartオフセットからend-1オフセットまでのシーケンスを抽出する
>>> letters = 'abcdefghijklmnopqrstuvwxyz'
>>> letters[5:10:2]
'fhj'
3.8. 長さの取得:len()
>>> len(letters)
26
3.9. 分割:split()
文字列関数split()
は、引数のセパレータを基準にして文字列を分割して、部分文字列のリストを返す。
>>> colors = 'red, green, blue, black, white'
>>> colors.split(',')
['red', ' green', ' blue', ' black', ' white']
3.10. 結合:join()
join()
関数は、split()
関数とは逆に、文字列のリストを一つの文字列に結合する。
>>> color_list = ['red', ' green', ' blue', ' black', ' white']
# string.join(list)
>>> colors = ','.join(color_list)
>>> print(colors)
red, green, blue, black, white
3.11. 多彩な文字列操作
両端の文字を削除する:string.strip()
引数で文字を指定すると、両端にあるその文字を削除する。
>>> sample = 'xxxabcxxxdefxxx'
>>> sample.strip('x')
'abcxxxdef'
引数を指定しない場合、次の空白文字を削除する。
- 半角スペース
- 全角スペース
- エスケープシーケンス(\n, \f, \t, \v, \r)
>>> sample = ' abc def '
>>> sample.strip()
'abc def'
3.12. 大文字と小文字の区別、配置
先頭の単語をタイトルケースにする。
# 聞くは一時の恥、聞かぬは一生の恥
>>> sample = 'better to ask the way than go astray.'
>>> sample.capitalize()
'Better to ask the way than go astray.'
すべての単語をタイトルケースにする。
>>> sample = 'better to ask the way than go astray.'
>>> sample.title()
'Better To Ask The Way Than Go Astray.'
すべての文字を大文字にする。
>>> sample = 'better to ask the way than go astray.'
>>> sample.upper()
'BETTER TO ASK THE WAY THAN GO ASTRAY.'
すべての文字を小文字にする。
>>> sample = 'better to ask the way than go astray.'
>>> sample.lower()
'better to ask the way than go astray.'
大文字小文字を逆にする。
>>> sample = 'better to ask the way than go astray.'
>>> sample.swapcase()
'BETTER TO ASK THE WAY THAN GO ASTRAY.'
指定した文字数の中で文字列を中央に配置する。
>>> sample = 'better to ask the way than go astray.'
>>> sample.center(60)
' better to ask the way than go astray. '
指定した文字数の中で文字列を左側に配置する。
>>> sample = 'better to ask the way than go astray.'
>>> sample.ljust(60)
'better to ask the way than go astray. '
指定した文字数の中で文字列を右側に配置する。
>>> sample = 'better to ask the way than go astray.'
>>> sample.rjust(60)
' better to ask the way than go astray.'
3.13. 置換:replace()
# string.replace(置き換えたい文字列, 置き換える文字列)
>>> sample = 'When in Rome do as the Romans do.'
>>> sample.replace('Rome', 'Japan')
'When in Japan do as the Romans do.'
参考資料
【書籍】
Python
Java
Discussion
bool型はint型のサブクラスで、Trueは1、Falseは0の値で実装されています。
なので、True + True が 2 になったり、比較結果を使った演算ができたりします。
この度は若輩者のためにご教示くださり、ありがとうございます。
bool型はint型のサブクラスである…、恥ずかしながら存じませんでした。
真偽値がブール代数で用いられ、二進数でも用いられる(変換できる)というのは、浅い知識の中でなんとなく認識していたつもりでしたが、実際にご提示いただいたような演算が可能であるとは知りませんでした。
私事ですが、これまでかいつまんだ知識でPythonを触っていたのですが、それゆえに基礎がおぼつかない危うさを身をもって実感することがあり、きちんと一から積み重ねたいと思い学び直しているところです。
まだ参考書をなぞるばかりで恥ずかしい身ではありますが、このようにご助言いただけますこと、大変ありがたく感じています。
若輩者ではございますが、気が向かれました際にまたご指導ご鞭撻いただけますと幸いに存じます。
この度はこのような粗末な記事に足を運んでいただきまして、誠にありがとうございました。