文字列
文字列は文字の列(シーケンス)のこと。文字列リテラルの表記方法は、以下の4つがある。
- シングルクオーテーション1個
‘string comes here’ - ダブルクオーテーション1個
“string comes here” - シングルクオーテーション3個
”’string comes here”’ - ダブルクオーテーション3個
“””string comes here”””
※シングルクオーテーションとダブルクオーテーションの違いは特にない。リテラル中にダブルクオーテーションを使う場合は、シングルクオーテーションを、リテラル中にシングルクオーテーションを使う場合はダブルクオーテーションを使うと楽。
文字列には、通常の文字列(‘str’型)と、ユニコード文字列(‘unicode’型)があります。
- 通常の文字列(str型)
“English only” - ユニコード文字列(unicode型)
u”日本語もOK”
文字列リテラルの例
一行の文字列
1 2 3 4 5 6 7 8 | >>> print "Hello World!" Hello World! >>> print 'Hello World!' Hello World! >>> print '"' " >>> print "'" ' |
複数行の文字列
複数行の文字列はダブルクオーテーション3個もしくは、シングルクオーテーション3個で囲む。
1 2 3 4 5 6 7 8 | >>> print """ ... Hello World! ... Hello World! ... """ >>> print ''' ... Hello World! ... Hello World! ... ''' |
日本語を含む文字列
日本語を含む文字列は、クオーテーションの前にuを付ける
1 2 3 4 5 6 7 8 9 10 | >>> print u"日本語" 日本語 >>> print u'日本語' 日本語 >>> print u"""日本語""" 日本語 >>> print u'''日本語''' 日本語 >>> print type(u'''日本語''') <type 'unicode'> |
文字列操作
- インデックス操作
位置指定で文字や部分文字列を抽出 - 連接
文字列を結合 - トリム(trim)
余分な空白を除去 - 分割(split)
カンマなどで分割 - マッチング
パターンマッチング
インデックス操作
インデックス指定で任意の文字を抽出できる。
1 2 3 4 5 6 7 8 9 10 | >>> "Hello"[0] 'H' >>> "Hello"[1] 'e' >>> "Hello"[2] 'l' >>> "Hello"[3] 'l' >>> "Hello"[4] 'o' |
負のインデックスを指定すると、末尾からの文字数指定になる。
1 2 3 4 5 6 7 8 9 10 | >>> "Hello"[-1] 'o' >>> "Hello"[-2] 'l' >>> "Hello"[-3] 'l' >>> "Hello"[-4] 'e' >>> "Hello"[-5] 'H' |
もちろん、変数に対しても同じことができる。
1 2 3 4 5 6 7 8 9 10 11 | >>> h = "Hello" >>> h[0] 'H' >>> h[1] 'e' >>> h[2] 'l' >>> h[3] 'l' >>> h[4] 'o' |
部分文字列の取り出し
1 2 3 4 5 6 | >>> "abcde"[0:3] 'abc' >>> "abcde"[1:3] 'bc' >>> "abcde"[2:3] 'c' |
引数は省略できる
1 2 3 4 5 6 | >>> "abcde"[:3] ##最初から3文字 'abc' >>> "abcde"[:] ##全体を取り出し 'abcde' >>> "abcde"[2:] ##3文字目から後ろ 'cde' |
引数には負の値を指定できる
1 2 3 4 5 6 7 8 | >>> "abcde"[-3:] ##後ろから3文字 'cde' >>> "abcde"[-2:] ##後ろから2文字 'de' >>> "abcde"[-1:] 'e' >>> "abcde"[-1] ##最後の1文字 'e' |
三番目の値で、STEPを指定できる。1だとすべての要素、2だと1つ飛ばし、-1だと逆順になる。
1 2 3 4 5 6 7 8 | >>> "Hello"[::1] 'Hello' >>> "Hello"[::2] 'Hlo' >>> "Hello"[::3] 'Hl' >>> "Hello"[::-1] 'olleH' |
連接
文字列の連結は+で行う。
1 2 | >>> "Hello"+" "+"World!" 'Hello World!' |
文字列に整数をかけると文字列の繰り返しになる。
1 2 | >>> "*"*30 '******************************' |
リストやタプルを結合する。
1 2 | >>> ",".join(["hello", "World"]) 'hello,World' |
文字列を分割してリストにする。
1 2 | >>> "a,b,c".split(",") ['a', 'b', 'c'] |
その他
rstrip: 行末の空白文字の除去。ユーザ入力の処理や、CSVインポート時に、行末のゴミを取り除く。
1 2 3 4 5 6 7 8 | >>> "ABCDE\n" 'ABCDE\n' >>> "ABCDE\n".rstrip() 'ABCDE' >>> "ABCDE\n\t".rstrip() 'ABCDE' >>> "ABCDE ".rstrip() 'ABCDE' |
find: 特定の文字が最初に出現する位置を返す
1 2 3 4 5 6 7 8 | >>> "abcde".find("a") ##1文字目は0に 0 >>> "abcde".find("c") 2 >>> "abcde".find("e") 4 >>> "abcde".find("f") ##見つからなければ-1に -1 |
upper 大文字に
lower 小文字に
1 2 3 4 | >>> "abcde".upper() 'ABCDE' >>> "ABCDE".lower() 'abcde' |
大文字にして小文字にしたら元通り。メソッドをつないでいけます。
1 2 | >>> "abcde".upper().lower() 'abcde' |
startswith: 特定の文字列で始まるか判定する
1 2 3 4 | >>> "hello".startswith("H") False >>> "hello".startswith("h") True |
endswith: 特定の文字列で終わるか判定する
1 2 3 4 | >>> "hello".endswith("o") True >>> "hello".endswith("O") False |
文字列オブジェクトの属性
文字列オブジェクトが持っている属性は以下のとおり。
1 2 3 4 5 6 7 8 9 10 11 | >>> dir("hoge") ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__g t__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__ ', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', ' __rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdi git', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lst rip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit' , 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', ' translate', 'upper', 'zfill'] |
文字列は非常によく使うオブジェクトです。__で囲まれているのは特殊な属性なので無視するとして、それ以外のメソッドは一通り機能を確認しておくとよいでしょう。