今さらPython3(7) - 文字列操作

このシリーズは、ハードル低めなので順調に進んでいますが、この本の第2章を読み進めています。今回は文字列の扱いのところから。

入門 Python 3

入門 Python 3

文字列のお約束

>>> 'Snap'
'Snap'
>>> "Crackle"
'Crackle'

'と"が両方使えるのは知ってます。

>>> "'Nay, ' said the naysayer."
"'Nay, ' said the naysayer."
>>> 'The rare double quote in captivity: ".'
'The rare double quote in captivity: ".'
>>> 'A "two by four" is actually 1 1/2" x 3 1/2".'
'A "two by four" is actually 1 1/2" x 3 1/2".'
>>> "'There's the man that shot my paw!' cried the liming hound."
"'There's the man that shot my paw!' cried the liming hound."

はいはい。両方使えるのは文字列の中にどちらかが混在しても大丈夫なようにですね。

>>> '''Boom!'''
'Boom!'
>>> ''Boom!''
  File "<stdin>", line 1
    ''Boom!''
         ^
SyntaxError: invalid syntax
>>> """Eek!!!"""
'Eek!!!'

'''か"""でもOK。複数行に跨がるときとか必要だねと。

>>> piem = '''There was a Young Lady of Norway,
... Who casually sat in a dooway;
... When the door squeezed her flat,
... She exclaimed, "What of that?"
... This courageous Young Lady of Norway.'''
>>> piem
'There was a Young Lady of Norway,\nWho casually sat in a dooway;\nWhen the door
 squeezed her flat,\nShe exclaimed, "What of that?"\nThis courageous Young Lady
of Norway.'
>>> poem = 'There was a young lady of Norway,
  File "<stdin>", line 1
    poem = 'There was a young lady of Norway,
                                            ^
SyntaxError: EOL while scanning string literal
>>>

スペルミスはスルーしておきましょう。(poem->piem)

>>> poem2 = '''I do not like three, Doctor Fell.
...     The reason why, I cannot tell.
...     But this I know, and know full well:
...     I do not like thee, Doctor Fell.
... '''
>>> print(poem2)
I do not like three, Doctor Fell.
    The reason why, I cannot tell.
    But this I know, and know full well:
    I do not like thee, Doctor Fell.

>>> print(piem)
There was a Young Lady of Norway,
Who casually sat in a dooway;
When the door squeezed her flat,
She exclaimed, "What of that?"
This courageous Young Lady of Norway.
>>>
>>> piem
'There was a Young Lady of Norway,\nWho casually sat in a dooway;\nWhen the door
 squeezed her flat,\nShe exclaimed, "What of that?"\nThis courageous Young Lady
of Norway.'

複数行で字下げしちゃうと、それもそのまま反映されちゃうということですね。あと、print文で出すと、きちんと改行を反映してくれると。

>>> print(99, 'bottles', 'would be enough.')
99 bottles would be enough.
>>> bottles = 99
>>> base = ''
>>> base += 'current inventory: '
>>> base += str(bottles)
>>> base
'current inventory: 99'
>>>

最初に''から始めているけど、別にそれに拘らなくていいやね。current inventoryを入れるときに=で行けば良いだけだと思うんだけどなぁ。


(つづく)