今さらPython3 (10) - 文字列いじり

この記事で2章が終わると良いな!

入門 Python 3

入門 Python 3

組み込み関数たち

>>> letters = 'abcdefghijklmnopqrstuvwxyz'
>>> len(letters)
26
>>> empty = ''
>>> len(empty)
0

定番のlen()はいいですね。

>>> todos = 'get gloves, get mask, give cat vitamins, call ambulance'
>>> todos.split(',')
['get gloves', ' get mask', ' give cat vitamins', ' call ambulance']
>>> todos.split()
['get', 'gloves,', 'get', 'mask,', 'give', 'cat', 'vitamins,', 'call', 'ambulance']
>>> set(todos.split())
{'mask,', 'cat', 'get', 'ambulance', 'give', 'gloves,', 'vitamins,', 'call'}
>>> 

救急車呼ぶのがtodoに入ってるのは変じゃね?というのはさておき、split()で分割しますと。引数渡すとその文字で分割して、空っぽの場合は空白で分割すると。最後にset使ったのは、getが重複してるのがちょっと気持ち悪かったからw

はいはい、今度はjoinですね。

>>> crypto_list = ['Yeti', 'Bigfoot', 'Loch Ness Monster']
>>> crypto_string = ', '.join(crypto_list)
>>> print('Found and signing book deals:', crypto_string)
Found and signing book deals: Yeti, Bigfoot, Loch Ness Monster
>>> 

個人的には、', '.join()という書き方が、あまり美しくないとは思うもの、文法だから仕方ないですね。

おさらい

よくつかう関数をおさらいしましょう。

>>> poem = '''All that doth flow we cannot liquid name
... Or else would fire and water be the same;
... But that is liquid which is moist and wet
... Fire that property can never get.
... Then 'tis not could that doth the fire put out
... But 'tis the wet that makes it die, no doubt.'''
>>> poem[:13]
'All that doth'
>>> len(poem)
251

ん?len(poem)が1文字多いなと思ったら、タイポですね。下から2行目のcoldをcouldと間違えとる。。。

>>> poem.startswith('All')
True
>>> poem.startswith('all')
False
>>> poem.endswith('That\'s all, folks!')
False

startswith()とendwiths()は当然のことながらcase sensitive(大文字小文字を判別する)と。

>>> word = 'the'
>>> poem.find(word)
73
>>> poem[73:3]
''
>>> poem[73:76]
'the'

find()で最初の出現箇所(オフセット)がわかるので、そこから3文字スライスすると'the'と返ってくる。

>>> poem.rfind(word)
215
>>> poem.count(word)
3
>>> poem.isalnum()
False
>>> 

rfind()は後ろから探す。出現回数をcount()で数える。isalnum()はアルファベットと数字だけで構成されているのかを確認。記号が混じっているからFalseという判断なのね。

さらに文字列操作系

>>> setup = 'a duck goes into a bar...'
>>> setup.strip('.')
'a duck goes into a bar'

ピリオド取り除いてねと。大文字小文字の変換に関しては、こんな感じ。

>>> setup.capitalize()
'A duck goes into a bar...'
>>> setup.title()
'A Duck Goes Into A Bar...'
>>> setup.upper()
'A DUCK GOES INTO A BAR...'
>>> setup.lower()
'a duck goes into a bar...'
>>> setup.swapcase()
'A DUCK GOES INTO A BAR...'

おっと。最後のやつは、本に書いてある結果と違うぞ?本の中で文字列はイミュータブルと言ってるんだから、正しくはこうやらないとダメでしょ?

>>> setup.capitalize().swapcase()
'a DUCK GOES INTO A BAR...'

でしょ?

>>> setup.center(40)
'       a duck goes into a bar...        '
>>> setup.center(41)
'        a duck goes into a bar...        '
>>> setup.center(42)
'        a duck goes into a bar...         '
>>> setup.ljust(30)
'a duck goes into a bar...     '
>>> setup.rjust(30)
'     a duck goes into a bar...'

センタリング、左寄せ、右寄せ。リスト的なものを出力する時とか使えそうですね。

>>> setup.replace('duck', 'marmoset')
'a marmoset goes into a bar...'
>>> setup.replace('a', 'a famous', 100)
'a famous duck goes into a famous ba famousr...'
>>> 

replace()はさっきも出たね。2つめは小文字のaを全部置き換えちゃうけど、そういう細かい条件は正規表現(第7章)でやるそうな。
これで第2章は完走。もっと詳しい話は、ドキュメントを読んでね。だそうです。

6.1. string — 一般的な文字列操作 — Python 3.4.3 ドキュメント

(つづく)