Skip to content

Instantly share code, notes, and snippets.

@Cartman0
Created March 31, 2016 11:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cartman0/bb974f82e8a3fc74ac82c3c2a5b1a4f9 to your computer and use it in GitHub Desktop.
Save Cartman0/bb974f82e8a3fc74ac82c3c2a5b1a4f9 to your computer and use it in GitHub Desktop.
Dive Into Python3 4章メモ(文字列)
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"metadata": {
"toc": "true"
},
"cell_type": "markdown",
"source": "# Table of Contents\n <p><div class=\"lev1\"><a href=\"#4章-文字列-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>4章 文字列</a></div><div class=\"lev2\"><a href=\"#飛び込む-1.1\"><span class=\"toc-item-num\">1.1&nbsp;&nbsp;</span>飛び込む</a></div><div class=\"lev2\"><a href=\"#文字列をフォーマットする-1.2\"><span class=\"toc-item-num\">1.2&nbsp;&nbsp;</span>文字列をフォーマットする</a></div><div class=\"lev3\"><a href=\"#合成フィールド名-1.2.1\"><span class=\"toc-item-num\">1.2.1&nbsp;&nbsp;</span>合成フィールド名</a></div><div class=\"lev3\"><a href=\"#フォーマット指定子-1.2.2\"><span class=\"toc-item-num\">1.2.2&nbsp;&nbsp;</span>フォーマット指定子</a></div><div class=\"lev2\"><a href=\"#その他の一般的な文字列メソッド-1.3\"><span class=\"toc-item-num\">1.3&nbsp;&nbsp;</span>その他の一般的な文字列メソッド</a></div><div class=\"lev3\"><a href=\"#文字列をスライスする-1.3.1\"><span class=\"toc-item-num\">1.3.1&nbsp;&nbsp;</span>文字列をスライスする</a></div><div class=\"lev2\"><a href=\"#文字列-vs-バイト列-1.4\"><span class=\"toc-item-num\">1.4&nbsp;&nbsp;</span>文字列 vs バイト列</a></div><div class=\"lev2\"><a href=\"#Pythonのソースコードの文字コード-1.5\"><span class=\"toc-item-num\">1.5&nbsp;&nbsp;</span>Pythonのソースコードの文字コード</a></div><div class=\"lev2\"><a href=\"#参考リンク-1.6\"><span class=\"toc-item-num\">1.6&nbsp;&nbsp;</span>参考リンク</a></div>"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "# 4章 文字列"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "http://diveintopython3-ja.rdy.jp/strings.html"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## 飛び込む"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "Python 3では、\n**すべての文字列はUnicode文字のシーケンス**だ。\nutf-8でエンコードされたPython文字列や、CP-1252でエンコードされたPython文字列というものは存在しない。\n\n**utf-8は文字列をバイト列としてエンコードする方法の1つ**。\n文字列を特定の文字コードでバイト列に変換したいのであれば、Python 3がそれを助けてくれる。\nバイト列を文字列に変換したいのであれば、それもPython 3が助けてくれる。バイトは文字ではない。\nバイトはただのバイトで、文字というのは抽象化であり、文字列はその抽象化のシーケンス。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "文字列を作るには、クォート文字で囲めばよい。Pythonの文字列はシングルクォート(')でもダブルクォート(\")でも定義できる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "組み込みのlen()関数は、文字列の長さ(つまり文字数)を返す。\nこの関数は、リスト・タプル・辞書・集合の長さを調べるときに使った関数と同じもの。"
},
{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "s = '深入 Python'\nlen(s)",
"execution_count": 1,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "9"
},
"metadata": {},
"execution_count": 1
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "リストから個々の要素を取り出すのとちょうど同じように、インデックス記法を使って文字列から個々の文字を取り出せる。"
},
{
"metadata": {
"trusted": true,
"collapsed": false,
"scrolled": true
},
"cell_type": "code",
"source": "s[0]",
"execution_count": 2,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "'深'"
},
"metadata": {},
"execution_count": 2
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "リストと同様に、文字列は+演算子で連結できる。"
},
{
"metadata": {
"trusted": true,
"collapsed": false,
"scrolled": true
},
"cell_type": "code",
"source": "s + ' 3'",
"execution_count": 3,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "'深入 Python 3'"
},
"metadata": {},
"execution_count": 3
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## 文字列をフォーマットする"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "Python 3は、値を文字列へフォーマットする機能をサポートしている。\n基本的な使い方は、1つのプレイスホルダを用いて文字列に値を挿入できる。"
},
{
"metadata": {
"trusted": true,
"collapsed": true
},
"cell_type": "code",
"source": "username = 'mark'\npassword = 'PapayaWhip' ",
"execution_count": 4,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "- これは文字列リテラルのメソッドを呼び出している。文字列はオブジェクトであり、オブジェクトはメソッドを持っているのだ。\n- この式全体が評価された結果は文字列になる。\n- {0}と{1}は「置換フィールド」であり、これらはformat()メソッドに渡された引数によって置換される。"
},
{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "\"{0}'s password is {1}\".format(username, password)",
"execution_count": 5,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "\"mark's password is PapayaWhip\""
},
"metadata": {},
"execution_count": 5
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "### 合成フィールド名"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "整数の置換フィールドは、format()メソッドに渡した引数の位置を示すインデックスとして扱われる。\n- {0}は1つ目の引数(この例ではusername)で置換され、\n- {1}は2つ目の引数(この例ではpassword)で置換される。\n\n引数は望むだけいくつでも与えることができ、その引数の数だけインデックスを使うことができる。しかし、置換フィールドはこれよりもっと強力な機能を持っている。"
},
{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "SUFFIXES = {1000: ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],\n 1024: ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']}\n\ndef approximate_size(size, a_kilobyte_is_1024_bytes=True):\n '''Convert a file size to human-readable form.\n\n Keyword arguments:\n size -- file size in bytes\n a_kilobyte_is_1024_bytes -- if True (default), use multiples of 1024\n if False, use multiples of 1000\n\n Returns: string\n\n ''' \n if size < 0:\n raise ValueError('number must be non-negative')\n\n multiple = 1024 if a_kilobyte_is_1024_bytes else 1000\n for suffix in SUFFIXES[multiple]:\n size /= multiple\n if size < multiple:\n return '{0:.1f} {1}'.format(size, suffix)\n \n \n",
"execution_count": 6,
"outputs": []
},
{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "si_suffixes = SUFFIXES[1000]\nsi_suffixes",
"execution_count": 7,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']"
},
"metadata": {},
"execution_count": 7
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "{0}とすれば、format()関数に与えられた1つ目の引数、つまりsi_suffixesを指すことになる。\nsi_suffixesはリストなので、\n- {0[0]}は、format()メソッドに1つ目の引数として与えられたリストの最初の要素、つまり'KB'を指している。\n- {0[1]}は同じリストの2つ目の要素、つまり'MB'を指している。\n\n波括弧の外側にあるすべてのもの、つまり1000、イコール記号、空白などはすべてそのままにされる。最終的な結果として'1000KB = 1MB'という文字列が得られる。"
},
{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "'1000{0[0]} = 1{0[1]}'.format(si_suffixes)",
"execution_count": 8,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "'1000KB = 1MB'"
},
"metadata": {},
"execution_count": 8
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "フォーマット指定子はPythonと(ほとんど)同じ構文でデータ構造の要素やプロパティにアクセスできるということだ。これは**合成フィールド名**と呼ばれる。次のような合成フィールド名が使える:"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "- リストを渡して、その要素にインデックスでアクセスする (先の例)\n- 辞書を渡して、その値にキーでアクセスする\n- モジュールを渡して、その変数や関数に名前でアクセスする\n- クラスインスタンスを渡して、そのプロパティやメソッドに名前でアクセスする\n- これらのどんな組み合わせも可能"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "- sysモジュールは、現在動作中のPythonインスタンスに関する情報を持っている。2行目でこれをインポートしたので、sysモジュール自体をformat()メソッドの引数として渡すことができる。したがって、{0}という置換フィールドはsysモジュールを指している。\n\n- sys.modulesは、このPythonインスタンスにおいてインポートされているすべてのモジュールから構成される辞書だ。その辞書のキーはモジュール名の文字列で、値はモジュールオブジェクトそのものだ。つまり置換フィールド{0.modules}はインポートされたモジュールの辞書を指している。\n\n- sys.modules['humansize']は、今インポートしたhumansizeモジュール。\n置換フィールドの{0.modules[humansize]}はhumansizeモジュールを指している。これはPythonのコードとはわずかに違う構文になっていることに注意しよう。\n実際のPythonコードでは、辞書sys.modulesのキーは文字列なので、モジュール名の周りをクォートで囲む必要がある(つまり'humansize'とする)。しかし置換フィールドの中では、辞書のキーの周りのクォートは省略する(つまりhumansizeとする)。\n\nPEP 3101: Advanced String Formattingにはこう書かれている。「要素のキーをパースする方法は非常に単純だ。数字から始まる場合は数値として扱われ、それ以外の場合は文字列として扱われる」\n\n- `sys.modules['humansize'].SUFFIXES` は、humansizeモジュールの先頭で定義されている辞書。\n置換フィールド{0.modules[humansize].SUFFIXES}は、この辞書を指している。\n\n- `sys.modules['humansize'].SUFFIXES[1000]`は、si接尾語のリスト['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']になる。\n\n- `sys.modules['humansize'].SUFFIXES[1000][0]`は、si接尾語のリストの最初の要素'KB'."
},
{
"metadata": {},
"cell_type": "markdown",
"source": "```\nimport humansize\nimport sys\n\n'1MB = 1000{0.modules[humansize].SUFFIXES[1000][0]}'.format(sys)\n\n'1MB = 1000KB'\n```"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "### フォーマット指定子"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "```\n'{0:.1f} {1}'.format(size, suffix)\n```\n\n{1}は、format()メソッドの2番目の引数suffixで置換される。\n\nこの後半部分(コロン以降)はフォーマット指定子というもので、置換する変数をどのようにフォーマットするのかをさらに詳細に指定するためのもの。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "フォーマット指定子は、C言語の `printf()` 関数のように、置換するテキストを様々な方法で加工できる。例えば、ゼロや空白でパディングしたり、文字列を揃えたり、小数の精度を整えたりできる。数値を16進数に変換することさえ可能."
},
{
"metadata": {},
"cell_type": "markdown",
"source": "- 置換フィールドの中では、コロン`(:)`はフォーマット指定子の開始を表す。\n\n- フォーマット指定子`“.1”`は「最も近い小数第1位の数へ丸める」ことを表す(つまり小数点の後ろには数字を1つだけ表示する)。\n\n- フォーマット指定子 `\"f\"` は「固定小数表記」にすることを表す(指数表記やその他の小数記法ではなく)。\n\nたとえば、698.24という値を持つsizeと、'GB'という値を持つsuffixを与えれば、698.24は小数第一位へ丸められ、そこに接尾語が付け足されることによって、フォーマット結果の文字列は'698.2 GB'になるだろう。"
},
{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "'{0:.1f} {1}'.format(698.24, 'GB')",
"execution_count": 9,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "'698.2 GB'"
},
"metadata": {},
"execution_count": 9
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## その他の一般的な文字列メソッド"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "フォーマットだけではなく、文字列には他にもいくつかの便利なテクニックがある。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "Pythonの対話シェルで複数行文字列を入力できる。\n三重クォート`'''`で複数行文字列を開始して、 ENTERキーを押すと、\n対話シェルは次行の入力をうながしてくる。\n三重クォートで文字列を終了させ、ENTERキーを押すとコマンドが実行される(この例では文字列がsという変数に代入される)。"
},
{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": " s = '''Finished files are the re-\n sult of years of scientif-\n ic study combined with the\n experience of years.'''",
"execution_count": 10,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "splitlines()メソッドは、複数行の文字列を受け取って、その文字列の各行からなる文字列のリストを返す。各行の行末にある改行文字は含まれないことに注意しよう。"
},
{
"metadata": {
"trusted": true,
"collapsed": false,
"scrolled": true
},
"cell_type": "code",
"source": "s.splitlines()",
"execution_count": 11,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "['Finished files are the re-',\n 'sult of years of scientif-',\n 'ic study combined with the',\n 'experience of years.']"
},
"metadata": {},
"execution_count": 11
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "lower()メソッドは文字列の全体を小文字に変換する\n(同様に、upper()メソッドは文字列を大文字に変換する)。"
},
{
"metadata": {
"trusted": true,
"collapsed": false,
"scrolled": true
},
"cell_type": "code",
"source": "print(s.lower())",
"execution_count": 12,
"outputs": [
{
"output_type": "stream",
"text": "finished files are the re-\nsult of years of scientif-\nic study combined with the\nexperience of years.\n",
"name": "stdout"
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "count()は、部分文字列が文字列中に出現する回数を数える。"
},
{
"metadata": {
"trusted": true,
"collapsed": false,
"scrolled": true
},
"cell_type": "code",
"source": "s.lower().count('f')",
"execution_count": 13,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "6"
},
"metadata": {},
"execution_count": 13
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "例えば、ここに\n`key1=value1&key2=value2` という形式の、キーと値のペアからなるリストがあるとする。これを分解して`{key1: value1, key2: value2}` のような辞書を作りたいとする。"
},
{
"metadata": {
"trusted": true,
"collapsed": true
},
"cell_type": "code",
"source": "query = 'user=pilgrim&database=master&password=PapayaWhip'",
"execution_count": 14,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "文字列の`split()`メソッドには、必ず引数として区切り文字を渡さなくてはならない。\nその区切り文字に基づいて、このメソッドは文字列をリストへ分割する。\nここでの区切り文字は`アンパサンド(&)`だが、どんな文字列でも区切り文字として使える。"
},
{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "a_list = query.split('&')\na_list",
"execution_count": 15,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "['user=pilgrim', 'database=master', 'password=PapayaWhip']"
},
"metadata": {},
"execution_count": 15
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "文字列のリストを手に入れた。各々の文字列には、キーがあり、その後ろにはイコール記号が続き、さらにその後ろに値が続く。\nリスト全体をイテレートして、各々の文字列を1つ目のイコール記号に基づいて2つに分割していくには、リスト内包表記が使える。\n\n`split()`メソッドの2番目の引数(オプション)は、 分割したい回数。\n1は「1回だけ分割する」ことを意味するので、split()メソッドは2つの要素をもつリストを返す。\n(理論上は、値がイコール記号を含んでいる可能性がある。もし、単純に'key=value=foo'.split('=')としていたら、\n結果として3つの要素を持つリスト['key'、'value'、'foo']が得られてしまうかもしれない)。"
},
{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "a_list_of_lists = [v.split('=', 1) for v in a_list if '=' in v]\na_list_of_lists",
"execution_count": 16,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "[['user', 'pilgrim'], ['database', 'master'], ['password', 'PapayaWhip']]"
},
"metadata": {},
"execution_count": 16
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "最後に、リストのリストをdict()関数に渡すだけで、Pythonはそれを辞書に変換してくれる。"
},
{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "a_dict = dict(a_list_of_lists)\na_dict",
"execution_count": 17,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "{'database': 'master', 'password': 'PapayaWhip', 'user': 'pilgrim'}"
},
"metadata": {},
"execution_count": 17
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "この例は、urlのクエリパラメータをパースしているように見えるが、\n現実世界のurlはこれよりも複雑。\nurlのクエリパラメータを扱うときは、`urllib.parse.parse_qs()関数`を使うと楽。この関数は特殊なケースもうまく扱ってくれる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "### 文字列をスライスする"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "文字列を定義したら、その文字列の一部を新しい文字列として取り出すことができる。これは文字列の「スライス」と呼ばれる。文字列のスライスはリストのスライスとまったく同様に動作する。"
},
{
"metadata": {
"trusted": true,
"collapsed": true
},
"cell_type": "code",
"source": "a_string = 'My alphabet starts where your alphabet ends.'",
"execution_count": 18,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "文字列の一部を取り出すことができる。この操作は「スライス」と呼ばれ、2つのインデックスを指定することによって行う。戻り値は新しい文字列であり、1つ目のスライスインデックス以降の文字を、順番どおりに含んでいる。"
},
{
"metadata": {
"trusted": true,
"collapsed": false,
"scrolled": true
},
"cell_type": "code",
"source": "a_string[3:11]",
"execution_count": 19,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "'alphabet'"
},
"metadata": {},
"execution_count": 19
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "リストのスライスと同様に、文字列のスライスには負のインデックスが使える。"
},
{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "a_string[3:-3]",
"execution_count": 20,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "'alphabet starts where your alphabet en'"
},
"metadata": {},
"execution_count": 20
}
]
},
{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "a_string[0:2]",
"execution_count": 21,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "'My'"
},
"metadata": {},
"execution_count": 21
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "左側のスライスインデックスが0のときはこれを省略できる。\nつまり、a_string[:18]はa_string[0:18]と同じ。"
},
{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "a_string[:18]",
"execution_count": 22,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "'My alphabet starts'"
},
"metadata": {},
"execution_count": 22
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "同様に、右側のスライスインデックスが文字列の長さと同じときはこれを省略できる。\nつまりa_string[18:]は、文字列の長さが44文字なので`a_string[18:44]` と同じになる。ここには気持ちの良い対称性が存在する。この44文字の文字列では、a_string[:18]は最初の18文字を返し、a_string[18:]最初の18文字以外を返す。実際に、文字列の長さにかかわらず、a_string[:n]は常に最初のn文字を返すし、a_string[n:]はその残りを返す。"
},
{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "a_string[18:]",
"execution_count": 23,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "' where your alphabet ends.'"
},
"metadata": {},
"execution_count": 23
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## 文字列 vs バイト列"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "バイトは単なるバイトであり、文字は抽象化だ。\n**Unicode文字のイミュータブルなシーケンスは「文字列」**と呼ばれ、\n**0から255までの数のイミュータブルなシーケンスは「バイト列」**と呼ばれる。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "bytesオブジェクトを定義するには、b''という「バイトリテラル」構文を使えばよい。\n\nバイトリテラルの各バイトには、\n- ascii文字\n- 16進数にエンコードされた\\x00から\\xffまでの数値 (0–255)\n\nが使える。"
},
{
"metadata": {
"trusted": true,
"collapsed": false,
"scrolled": true
},
"cell_type": "code",
"source": "by = b'abcd\\x65'\nby",
"execution_count": 24,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "b'abcde'"
},
"metadata": {},
"execution_count": 24
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "bytesオブジェクトの型はbytes。"
},
{
"metadata": {
"trusted": true,
"collapsed": false,
"scrolled": true
},
"cell_type": "code",
"source": "type(by)",
"execution_count": 25,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "bytes"
},
"metadata": {},
"execution_count": 25
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "リストや文字列と同様に、+演算子を使ってbytesオブジェクトを連結できる。\n結果は新しいbytesオブジェクト。"
},
{
"metadata": {
"trusted": true,
"collapsed": false,
"scrolled": true
},
"cell_type": "code",
"source": "by += b'\\xff'\nby",
"execution_count": 26,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "b'abcde\\xff'"
},
"metadata": {},
"execution_count": 26
}
]
},
{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "len(by)",
"execution_count": 27,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "6"
},
"metadata": {},
"execution_count": 27
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "リストや文字列と同様に、インデックス記法によってbytesオブジェクトの個々のバイトを取り出せる。\n文字列の要素は文字列だが、\n**bytesオブジェクトの要素は整数**。厳密に言えば、0から255までの整数だ。"
},
{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "by[0]",
"execution_count": 28,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "97"
},
"metadata": {},
"execution_count": 28
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "bytesオブジェクトはイミュータブル。\n個々のバイトへ代入することはできない。もし個々のバイトを変更する必要があるときは、文字列スライスと結合演算子(これは文字列と同様に機能する)を使うこともできるし、bytesオブジェクトをbytearrayオブジェクトに変換することもできる。"
},
{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "by[0] = 102",
"execution_count": 29,
"outputs": [
{
"output_type": "error",
"ename": "TypeError",
"evalue": "'bytes' object does not support item assignment",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m<ipython-input-29-bb4ece50b6ff>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mby\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m]\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;36m102\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[1;31mTypeError\u001b[0m: 'bytes' object does not support item assignment"
]
}
]
},
{
"metadata": {
"trusted": true,
"collapsed": true
},
"cell_type": "code",
"source": "by = b'abcd\\x65'",
"execution_count": 30,
"outputs": []
},
{
"metadata": {},
"cell_type": "markdown",
"source": "bytesオブジェクトを変更可能なbytearrayオブジェクトに変換するには、組み込みのbytearray()関数を使う。"
},
{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "barr = bytearray(by)\nbarr",
"execution_count": 31,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "bytearray(b'abcde')"
},
"metadata": {},
"execution_count": 31
}
]
},
{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "len(barr)",
"execution_count": 32,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "5"
},
"metadata": {},
"execution_count": 32
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "byteとbytearrayの1つの違いは、\nbytearrayオブジェクトではインデックス記法を使って個々のバイトへ代入できる。代入する値は0から255までの整数でなければならない。"
},
{
"metadata": {
"trusted": true,
"collapsed": false,
"scrolled": true
},
"cell_type": "code",
"source": "barr[0] = 102\nbarr",
"execution_count": 33,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "bytearray(b'fbcde')"
},
"metadata": {},
"execution_count": 33
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "バイト列と文字列は決して混ぜることができない。"
},
{
"metadata": {
"trusted": true,
"collapsed": true
},
"cell_type": "code",
"source": "by = b'd'\ns = 'abcde'",
"execution_count": 34,
"outputs": []
},
{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "by + s",
"execution_count": 35,
"outputs": [
{
"output_type": "error",
"ename": "TypeError",
"evalue": "can't concat bytes to str",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m<ipython-input-35-2752bca4b043>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mby\u001b[0m \u001b[1;33m+\u001b[0m \u001b[0ms\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[1;31mTypeError\u001b[0m: can't concat bytes to str"
]
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "バイト列が文字列中に出現する回数を数えることはできない。文字列の中にバイト列というものは存在しない。\n\n文字列は文字のシーケンス。 \nもしかすると「バイト列を特定の文字コードを使って文字列にデコードし、その文字列の出現回数を数えよ」ということをしたいのであれば、\nそれを明示的に行う必要がある。\n\n**Python 3が暗黙にバイト列を文字列に変換したり、文字列をバイト列に変換することはない**。"
},
{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "s.count(by)",
"execution_count": 36,
"outputs": [
{
"output_type": "error",
"ename": "TypeError",
"evalue": "Can't convert 'bytes' object to str implicitly",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m<ipython-input-36-14a8d8da7d7a>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0ms\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mcount\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mby\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[1;31mTypeError\u001b[0m: Can't convert 'bytes' object to str implicitly"
]
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "この行のコードは、「このバイト列を指定した文字コードでデコードして得られる文字列の出現回数を数えよ」"
},
{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "s.count(by.decode('ascii'))",
"execution_count": 37,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "1"
},
"metadata": {},
"execution_count": 37
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "文字列とバイト列のあいだの関係:\n- bytesオブジェクトはdecode()メソッドを持っていて、これは文字コードを受け取って文字列を返す。\n\n- 文字列はencode()メソッドを持っていて、これは文字コードを受け取ってbytesオブジェクトを返す。\n\n前の例は、asciiコードのバイト列を文字列に変換するというもので、デコード処理は比較的単純だ。しかし同様の処理は、文字列に含まれている文字をサポートしているものなら、どんな文字コードでも(非Unicodeエンコーディングでも)動作する。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "文字列。9つの文字を含んでいる。"
},
{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "a_string = '深入 Python'\nlen(a_string)",
"execution_count": 38,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "9"
},
"metadata": {},
"execution_count": 38
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "bytesオブジェクトで、13バイトある。これはa_stringをutf-8でエンコードしたときに得られるバイト列。"
},
{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "by = a_string.encode('utf-8')\nby",
"execution_count": 39,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "b'\\xe6\\xb7\\xb1\\xe5\\x85\\xa5 Python'"
},
"metadata": {},
"execution_count": 39
}
]
},
{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "len(by)",
"execution_count": 40,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "13"
},
"metadata": {},
"execution_count": 40
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "これはa_stringをGB18030でエンコードしたときに得られるバイト列。"
},
{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "by = a_string.encode('gb18030')\nby",
"execution_count": 41,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "b'\\xc9\\xee\\xc8\\xeb Python'"
},
"metadata": {},
"execution_count": 41
}
]
},
{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "len(by)",
"execution_count": 42,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "11"
},
"metadata": {},
"execution_count": 42
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "bytesオブジェクトで、11バイトある。これはa_stringをBig5でエンコードしたときに得られるもので、先のものとは全く異なったバイト列になっている。"
},
{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "by = a_string.encode('big5')\nby",
"execution_count": 43,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "b'\\xb2`\\xa4J Python'"
},
"metadata": {},
"execution_count": 43
}
]
},
{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "len(by)",
"execution_count": 44,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "11"
},
"metadata": {},
"execution_count": 44
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "これは文字列で、9つの文字がある。\nこれはbyをBig5エンコーディングアルゴリズムでデコードしたときに得られる文字列。これは元の文字列に等しい。"
},
{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "roundtrip = by.decode('big5')\nroundtrip",
"execution_count": 45,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "'深入 Python'"
},
"metadata": {},
"execution_count": 45
}
]
},
{
"metadata": {
"trusted": true,
"collapsed": false
},
"cell_type": "code",
"source": "a_string == roundtrip",
"execution_count": 46,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": "True"
},
"metadata": {},
"execution_count": 46
}
]
},
{
"metadata": {},
"cell_type": "markdown",
"source": "## Pythonのソースコードの文字コード"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "Python3は、ソースコード(つまり.pyファイル)がutf-8でエンコードされていると想定する。"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "もしPythonのコードで異なる文字コードを使いたい場合は、文字コード宣言を各ファイルの先頭に書くことができる。\n\n次の宣言は、.pyファイルの文字コードをwindows-1252に設定している:\n\n```\n# -*- coding: windows-1252 -*-\n```"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "厳密に言うと、1行目がunix系環境で使われるシェバン (#!) である場合は、文字コードの宣言は2行目でもよい。\n\n```\n#!/usr/bin/python3\n# -*- coding: windows-1252 -*-\n```"
},
{
"metadata": {
"trusted": true,
"collapsed": true
},
"cell_type": "markdown",
"source": "## 参考リンク"
},
{
"metadata": {},
"cell_type": "markdown",
"source": "- [Dive Into Python3 4章 文字列](http://diveintopython3-ja.rdy.jp/strings.html)"
}
],
"metadata": {
"toc": {
"toc_threshold": "6",
"toc_cell": true,
"toc_window_display": false,
"toc_number_sections": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3",
"language": "python"
},
"language_info": {
"pygments_lexer": "ipython3",
"mimetype": "text/x-python",
"file_extension": ".py",
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"version": "3.5.1",
"name": "python",
"nbconvert_exporter": "python"
},
"gist": {
"id": "",
"data": {
"description": "Dive Into Python3 4章メモ(文字列)",
"public": true
}
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment