3. 形式ばらない Python の紹介 (文字列型)
Python チュートリアル — Python 3.6.13 ドキュメント
3. 形式ばらない Python の紹介 3.1. Python を電卓として使う 3.1.1. 数 3.1.2. 文字列型 (string) 3.1.3. リスト型 (list) 3.2. プログラミングへの第一歩
- 文字列型(string)
> python >>> 'spam eggs' 'spam eggs' >>> 'doesn\'t' "doesn't"
- 変数に格納した改行(\n)は出力方法によって動作が異なるらしい…。
>>> s = 'First line.\nSecond line.' >>> s 'First line.\nSecond line.' >>> print(s) First line. Second line. >>>
- 「\n」という文字列を改行したくない場合は「raw string」という仕組みが使えるらしい
>>> print('C:\some\name') C:\some ame >>> print(r'C:\some\name') C:\some\name >>> # エスケープ記号(\)をエスケープしてもよいけど、出力したい文字列と入力文字列が異なって面倒…。 >>> print('C:\some\name') C:\some\name # 変数に格納してprintするときはraw stringとして代入しておく必要がありそう ## NG >>> a ='C:\some\name' >>> a 'C:\\some\name' >>> print(a) C:\some ame >>> ## OK >>> b =r'C:\some\name' >>> b 'C:\\some\\name' >>> print(b) C:\some\name >>>
- 複数行の文字列の表示
>>> print("""\ ... Usage: thingy [OPTIONS] ... -h Display this usage message ... -H hostname Hostname to connect to ... """) Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to >>>
- 文字列と演算子(加算・乗算)
>>> 3 * 'un' + 'ium' 'unununium'
- 並んだ文字列はそのまま出力(自動連結)される
>>> 'Py' 'thon' 'Python'
# test.py print('Py' 'thon')
> python test.py Python >
- 文字列の自動連結は変数や式には無効…。
>>> a = 'Py' >>> b = 'thon' >>> a b File "<stdin>", line 1 a b ^ SyntaxError: invalid syntax # 変数の文字列結合は「+」を使う >>> a+b 'Python' >>>
- 文字列は配列的に扱える
>>> word = 'Python' # 添字(index,subscript)(正の数) >>> word[0] 'P' >>> word[5] 'n' # 添字(index,subscript)(負の数) >>> word[-1] 'n' >>> word[-6] 'P' # 添字(index,subscript)(スライス) >>> word[0:2] 'Py' >>> word[2:6] 'thon' # 大きすぎる添字はエラー >>> word[100] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: string index out of range # でもスライスは適切に扱ってくれる…。 >>> word[1:100] 'ython' >>> word[10:100] '' >>> >>>
- 文字列の各要素は不変(immutable)
>>> word = 'Python' >>> word[0] = 'J' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object does not support item assignment >>>
- だけど文字列の変数には再代入可能…。
>>> word = 'Python' >>> word 'Python' >>> word = 'Jython' >>> word 'Jython' >>>
- 組込み関数「len()」は文字列の長さを返す。
>>> len(word) 6 >>>
参考
参考に記載のあるリンクの情報が、実は大切そう。だけど、Tutorial的には「参考」なので、いったんスルー…。 - 4. 組み込み型 — Python 3.6.13 ドキュメント - 4. 組み込み型 — Python 3.6.13 ドキュメント - 2. 字句解析 — Python 3.6.13 ドキュメント - 6.1. string --- 一般的な文字列操作 — Python 3.6.13 ドキュメント - 4. 組み込み型 — Python 3.6.13 ドキュメント