はじめに

プログラミング超初心者が初心者になるためのPython入門(1)
 セットアップ・文字列・数値編 Kindle版
www.amazon.co.jp/dp/B00SH9TZV6

  • 上記の書籍を基に学習した際のまとめです
  • 書籍ではPython2.7をベースに書かれていますが、Python3に置き換えて手元の環境で実行した内容を載せています
  • リファレンスを参照して追加で情報を載せている部分もあります

(1)セットアップ・文字列・数値編

セットアップ

  • Pythonのインストール(Win/Mac)
  • 開発環境のIDLEを使う

IDLEはPythonをインストールした際に一緒についてくる。以下のような対話形式のコンソール画面。

idle.PNG

IDLEで.pyファイルを作成、編集して、F5でrunさせることもできる。
Alt + pでWindowsのコマンドプロンプトで「↑」を押したときと同じように、過去の入力内容を表示させることができる。Alt + Nで進む。

隠しコマンド的なもの。
The Zen of Pythonというものらしい。
https://www.python.org/dev/peps/pep-0020/

import_this
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

基本的に以下においては、手元のIDLEの環境で実行した内容を記載していく。

文字列

  • printによる文字列の出力
  • +を用いた文字列の結合
  • 文字列を囲むときは" "' 'を使う
  • #でコメントを入れることができる
  • 日本語はマルチバイトなので場合によっては注意

splitメソッド

ここで初めてメソッドという言葉が登場する。
ここでは「お尻につけると便利な働きをしてくれるコマンド」と表現されている。

文字を分割するメソッド。

split
>>> print("Hello World".split("e"))  # splitの引数に区切りの文字を指定
['H', 'llo World']

>>> print("Hello World".split())  # 引数を指定しないと空白文字で区切る
['Hello', 'World']

>>> print("Hello World".split("o",1))  # 数字を指定するとその回数分区切る
['Hell', ' World']

>>> print("Hello World".split("o",2))
['Hell', ' W', 'rld']

本書では触れられていないが、[ ]で区切られたリスト(配列)で返される。

公式リファレンス
https://docs.python.org/ja/3/library/stdtypes.html#str.split

リファレンスも初めて見た時はとっつきづらかった。

str.split(sep=None, maxsplit=-1)

列を sep をデリミタ文字列として区切った単語のリストを返します。maxsplit が与えられていれば、最大で maxsplit 回分割されます (つまり、リストは最大 maxsplit+1 要素になります)。 maxsplit が与えられないか -1 なら、分割の回数に制限はありません (可能なだけ分割されます)。

文字列にアクセスするメソッドで、引数を2つ(sep,maxsplit)指定する。
入力を省略した場合は、それぞデフォルトの値として指定されているNone,-1を渡したものとみなされる。
sepやmaxsplitとは、引数の働きを分かりやすくするためにメソッドごとに定められている変数である、と捉えた。単なる引数の名称とのこと。組み込みものでなく、自分で関数を定義することに慣れてくると理解が進みそう。

4.7. 関数定義についてもう少し
https://docs.python.org/ja/3/tutorial/controlflow.html#more-on-defining-functions

replaceメソッド

置換するメソッド。

replace
>>> print("Hello World".replace("o","a"))  # 引数1つ目の文字列を2つ目のものに置換
Hella Warld

>>> print("Hello World".replace("o","a",1))  # 数字を指定すると、先頭からその個数分だけ置換
Hella World

公式リファレンス
https://docs.python.org/ja/3/library/stdtypes.html#str.replace

str.replace(old, new[, count])

文字列をコピーし、現れる部分文字列 old 全てを new に置換して返します。オプション引数 count が与えられている場合、先頭から count 個の old だけを置換します。

リファレンスにおいて[ ]で囲まれている場合は、引数として指定が必須ではないことを表す。

upperメソッド、lowerメソッド

大文字化、小文字化するメソッド。

upper_lower
>>> print("Hello World".upper())  # 大文字小文字の区別があるものをすべて大文字化する
HELLO WORLD

>>> print("Hello World".lower())  # 大文字小文字の区別があるものを小文字化する
hello world

引数は取らないらしい。

公式リファレンス
https://docs.python.org/ja/3/library/stdtypes.html#str.upper
https://docs.python.org/ja/3/library/stdtypes.html#str.lower

メソッドは組み合わせることもできる。(ここでは単にメソッドをつなげて使うことを組み合わせると表現している。)

メソッドの組み合わせ
>>> print("Hello World".upper().split("O"))  # splitには大文字Oを指定
['HELL', ' W', 'RLD']

>>> print("Hello World".upper().split("o"))  # splitには小文字のoを指定
['HELLO WORLD']

変数を使用した例

  • 変数に文字列を入れる
  • 変数に入れた文字列にメソッドを使う
  • 変数に変数を入れる
変数と組み合わせた例
>>> x = "Hello World"
>>> print(x.upper())
HELLO WORLD

>>> x = "Hello World"
>>> x = x.upper()  # 変数xの中身を上書き
>>> print(x)
HELLO WORLD

joinメソッド

結合するメソッド。

join
>>> x = "Hello World".split()
>>> print(x)
['Hello', 'World']

>>> print("".join(x))  # joinの前の文字列で引数を結合する
HelloWorld

>>> print("_and_".join(x))
Hello_and_World

公式リファレンス
https://docs.python.org/ja/3/library/stdtypes.html#str.join

joinメソッドの引数はiterableでなければならない。
iterableとは、配列やタプル、辞書型などの、for <変数> in xxxで要素を1つずつ返せるものを指す。

https://docs.python.org/ja/3/glossary.html#term-iterable

findメソッド

検索して位置を返してくれるメソッド。

find
>>> "Hellow World".find("l")  # 小文字の"l"が登場する番号を返す
2
>>> "Hello World"[0]  # 文字列の先頭は0からカウントが始まる
'H'
>>> "Hello World".find("l",3)  # 検索する文字の後に数字を指定すると検索の開始位置を指定できる
3
>>> "Hello World".find("l",5)
9
>>> "Hello World".find("l",5,7)  # さらに数字を引数として渡すと検索の終了位置を定義 
-1  # 検索に引っ掛からない場合は-1

公式リファレンス
https://docs.python.org/ja/3/library/stdtypes.html#str.find

countメソッド

条件に一致する数を数えるメソッド。

count
>>> "Hello World".count("o")  # 文字列の中から"o"の個数をカウント
2
>>> "Hello World".count("l")  # "l"の個数をカウント
3
>>> "Hello World".count("l",3)  # 検索の開始位置を指定できる
2
>>> "Hello World".count("l",3,7)  # 検索の終了位置も指定できる
1
>>> "Hello World".count("ll")  # カウント対象は1文字である必要はない
1

公式リファレンス
https://docs.python.org/ja/3/library/stdtypes.html#str.count

インデクシング

ある固まりから、インデックス(番号、指標)を指定して取り出す操作のことを指していると捉えた。ここでの固まりは先述のiterableとイコールであると思っているが調べきれていない。

(追記:コメントいただき、iterableである必要はないとのこと。)

インデクシング
>>> x = "Hello World"
>>> print(x[1])
e  # 0から始まるので、左から2番目の文字が返り値
>>> print(x[5])
   # 半角スペースが返ってきている
>>> print(x[-1])
d  # 右端が-1
>>> print(x[-10])
e  # 左から2番目であり右から10番目でもある

>>> y = ["aa","bb","cc"]
>>> print(y[1])
bb  # 配列でもインデクシングできる

スライシング

インデクシングはピンポイントでの指定だったが、スライシングでは範囲で指定できる。

スライシング
>>> x = "Hello World"
>>> print(x[2:7])
llo W  # [2]から[6]までの範囲([7]は含まない)
>>> print(x[4:])
o World  # [4]以降の範囲
>>> print(x[:9])
Hello Wor  # [0]から[8]までの範囲
>>> print(x[:])
Hello World  # すべて

>>> y = ["aa","bb","cc"]
>>> print(y[1:])
['bb', 'cc']  # もちろん配列でもできる

その他

  • IDLEでの対話型でなく.pyファイルを作成して実行する
    • 環境変数を設定してパスを通す
  • コマンドプロンプトでの対話型を試す

数値型

  • データ型の概念
  • type関数で型を確認
type
>>> type("Hello World")
<class'str'>    # 文字列
>>> type(3)
<class'int'>    # 整数
>>> type(6.02)
<class'float'>    # 浮動小数点数
>>> type(['a','b'])
<class'list'>    # 配列
>>> type(('a','b'))
<class'tuple'>    # タプル
>>> type(True)
<class'bool'>    #  真偽
>>> type({1:'a',2:'b'})
<class'dict'>    # 辞書
>>> type(set([1,1,1,2,2,3]))
<class'set'>    # 集合

公式リファレンス
https://docs.python.org/ja/3/library/functions.html#type

データ型の種類をリファレンス上で一覧で確認できたりするのかと思ったが、そう単純ではないようだ。

四則演算

+-*/

計算
>>> 1+5  # スペースを入れなくてもいい
6
>>> 1    +       5  # スペースをたくさん入れてもいい
6
>>> 1/5  # python2の頃は整数同士の計算だと結果も整数に丸められたらしい
0.2  # python3では自動で浮動小数点数にしてくれる
>>> 10/3
3.3333333333333335  # 最後が5の理由はちょっと分からない
>>> "Hello" * 4  # 文字列に * を使うことができる
'HelloHelloHelloHello'

数値型と文字列の混在

int関数とstr関数
>>> x = 7
>>> print("Lucky" + x)  # 文字列と数値の結合を試行していることになる
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    print("Lucky" + x)
TypeError: must be str, not int  # 型が違うのでエラーが出る

>>> str(x)  # 文字列に変換する
'7'
>>> print("Lucky" + str(x))
Lucky7

>>> y = '8'  # 文字列
>>> x + y  # 数値と文字列の結合を試行していることになる
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    x + y
TypeError: unsupported operand type(s) for +: 'int' and 'str'  # エラーが出る


>>> int(y)  # 整数に変換する
8
>>> x + int(y)
15

formatメソッド

メソッドが参照する文字列内の置換フィールドに、引数の文字列を入れて返すイメージ。

formatメソッド
>>> x = "Jhon"
>>> y = "Yoko"
>>> z = "I am {}. You are {}."  # 置換フィールドに何も指定しない場合
>>> print(z.format(x,y))
I am Jhon. You are Yoko.  # 引数が順番に割り当てられる

>>> z2 = "I am {0}. You are {1}."  # インデックスの番号を指定
>>> print(z2.format(x,y))
I am Jhon. You are Yoko.  # 置換フィールドがブランクの場合と同様

>>> z3 = "I am {1}. You are {0}."  # [1」を先に指定
>>> print(z3.format(x,y))
I am Yoko. You are Jhon.  # 2つ目の引数yが先に来ている

引数が文字列でない場合は文字列に変換したものを入れて返すイメージ。

formatに数字
>>> n = 33  # 数値型
>>> z = "I am {}. You are {}."
>>> print(z.format(n,n))  # 引数として渡している時点ではnは数値型
I am 33. You are 33.  # 出力結果は文字列型

>>> type(n)
<class'int'>

>>> type(z.format(n,n))
<class'str'>

公式リファレンス
https://docs.python.org/ja/3/library/stdtypes.html#str.format

%を使う書き方

%を使ってformatメソッドと似たようなことができる。

%を使う書き方
>>> X = "Jhon"
>>> Y = "Yoko"
>>> Z = "I am %s. You are %s"  # %sはstring(文字列)のs

>>> print(Z %(X,Y))
I am Jhon. You are Yoko
>>> print(Z %(Y,X))
I am Yoko. You are Jhon

%を用いて数値を入れる際は、%d(digitのd)を用いる。
今回の例だと%sで指定している個所の引数に数値を入れるのはOKだが、%dのところに文字列を入れるのはNGのようだ。

%dを使う書き方
>>> N = 33
>>> Z2 = "I am %s. You are %d"

>>> print(Z2 %(X,N))  # %sに文字列、%dに数値
I am Jhon. You are 33

>>> print(Z2 %(N,X))  # %sに数値、%dに文字列
Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    print(Z2 %(N,X))
TypeError: %d format: a number is required, not str

>>> print(Z2 %(N,N))  # %sにも%dにも数値
I am 33. You are 33

(追記:3.6から追加されたf-stringというものでも同じようなことができるのこと)
https://docs.python.org/ja/3/reference/lexical_analysis.html#formatted-string-literals

最後にまた文字列

改行

nを入れると改行される。

改行
>>> print("Hellow nWorld")
Hellow 
World

centerメソッド

引数に指定した数値の幅で中央寄せして表示する。2つ目の引数を渡すとその値で埋められる。

center
>>> print("Hello".center(20))
       Hello        
>>> print("Hello".center(30))
            Hello
>>> print("Hello".center(30,"i"))
iiiiiiiiiiiiHelloiiiiiiiiiiiii

公式リファレンス
https://docs.python.org/ja/3/library/stdtypes.html#str.center

rjust、ljustメソッド

centerメソッドと同じ考え方で、それぞれ右寄せ、左寄せ。

rjust_ljust
>>> print("Hello".rjust(26,"r"))
rrrrrrrrrrrrrrrrrrrrrHello
>>> print("Hello".ljust(14,"l"))
Hellolllllllll

公式リファレンス
https://docs.python.org/ja/3/library/stdtypes.html#str.center
https://docs.python.org/ja/3/library/stdtypes.html#str.ljust

成形済みの文章を入力するパターン

ダブルクォーテーション3つ
>>> """  # ダブルクォーテーション3つ入力し
Hello     # 成形済みの文章をペースト
     Hello
          Hello"""  # 末尾にも3つ
'nHellon     Hellon          Hello'  # 先頭で改行しているのでnが入っている

>>> """Hello  # ダブルクォーテーションの後に改行を入れないパターン
     Hello
          Hello"""
'Hellon     Hellon          Hello'  # 先頭に改行が入らない

>>> print("""Hello
     Hello
          Hello""")
Hello
     Hello
          Hello

(1)セットアップ・文字列・数値編はここまで。

おわりに

Kindle unlimitedに登録していれば無料で読めるので、スマホに入れてサラッと読むだけでもとっかかりとしてはかなり良かったです。完全に割り切って「本書ではこれについて詳細は説明しません」とされている部分もしばしばあり、順番に学習していける感があります。

市販の書籍よりも易しいレベルで書かれているので、タイトルの通り超初心者にとってはおすすめできる入門書です。私は市販の書籍と並行して読んでいましたが、それぞれ基本的な概念をどういったアプローチで教えようとしているかが違って面白かったです。

TOP