ページへ戻る

− Links

 印刷 

Python​/文字列の分割 :: NJF Wiki

xpwiki:Python/文字列の分割

区切り文字による分割 anchor.png[1] Edit [2]

区切り文字をつかって文字列を分解するのは「split」を使います。

testStr = "a,b,c,d,e,f"

print testStr.split(",")

結果

['a', 'b', 'c', 'd', 'e', 'f']

splitには第2引数に分割する回数を指定できます。

testStr = "a,b,c,d,e,f"

print testStr.split(",",2)

結果

['a', 'b', 'c,d,e,f']

Unicodeでも同じです。

Page Top

すべてばらばらにする anchor.png[3] Edit [4]

Pythonのsplitは空文字列で分割できないため、1文字ずつにしたいならlist関数を使います。

testStr = "123456789"

print list(testStr)

結果

['1', '2', '3', '4', '5', '6', '7', '8', '9']

ただし、Pythonの文字列はもともとリストのような振る舞いをするので、参照するだけならリストに変換してもさほど使い道はないかも知れません。

例えば、文字列のままでループも可能です。

testStr = "123456789"

for c in testStr:
    print c

結果

1
2
3
4
5
6
7
8
9

しかし、頻繁に大きな文字列を編集するならリストの方が高速なので、その場合に文字列のリストへの変換が役立つことがあります。


Last-modified: 2017-09-05 (火) 06:40:09 (JST) (2415d) by njf