ホーム >  Python >  pythonの文字列とプレースホルダー

投稿日:   |  最終更新日:

pythonの文字列とプレースホルダー

Python

文字列

文字列を変数に代入

>>> fred = silly_string = 'Why do gorillas have big nostrils? Big fingers!!'

文字列を変数に代入するには、文字列の最初と最後をシングルクオーテーションで囲みます。

>>> fred = silly_string = "Why do gorillas have big nostrils? Big fingers!!"

ダブルクオーテーションで囲んでも正しく代入できます。

複数行の文字列を変数に代入

>>> fred = silly_string = 'How do dinosaurs pay their bills?
SyntaxError: EOL while scanning string literal

silly_string = How do dinosaurs pay their bills?
クオート文字で文字列を終了させないままEnterキーをクリックします。
すると、「SyntaxError: EOL while scanning string literal」エラーが表示されます。

silly_string = ”’How do dinosaurs pay their bills?
With tyrannosaurus checks!”’
複数行の文字列を作りたい場合は、クオート文字を三つ連続して書きます。

文字列の中にシングルクオーテーションやダブルクオーテーションを含む場合

>>> silly_string = silly_string = 'He said, "Aren't can't shouldn't wouldn't"'
SyntaxError: invalid syntax

He said, “Aren’t can’t shouldn’t wouldn’t”
上記の文字列は、最初と最後をシングルクオーテーションで正しく囲んでます。
しかし、文字列の中にシングルクオーテーションを含んでいますので「SyntaxError」が出ます。

>>> silly_string = '''He said, "Aren't can't shouldn't wouldn't"'''

”’He said, “Aren’t can’t shouldn’t wouldn’t””’
文字列を正しく変数に代入するには、最初と最後をシングルクオーテーション3つで囲みます。

>>> silly_string = 'He said, "Aren\'t can\'t shouldn\'t wouldn\'t"'

He said, “Aren\’t can\’t shouldn\’t wouldn\’t”
バックスラッシュ文字をクオート文字の前に記述する方法もあります。
これを「エスケープ」と呼びます。

プレースホルダーでデータを文字列に埋め込む

>>> myscore = 100
>>> message = 'I scored %s points'
>>> print(message % myscore)
I scored 100 points

変数に代入されたデータをメッセージに使います。
文字列に変数のデータを埋め込むには、文字列中に「%s」を記述します。
「%」を使った埋め込み場所を示すマークをプレースホルダーと呼びます。

複数の変数を埋め込む場合

>>> joke_text = '%s: a device for finding furniture in the dark'
>>> bodypart1 = 'knee'
>>> bodypart2 = 'shin'
>>> print(joke_text % bodypart1)
knee: a device for finding furniture in the dark
>>> print(joke_text % bodypart2)
shin: a device for finding furniture in the dark

違う内容の2つの変数を使うことで、2つの異なる結果が得られます。

複数プレースホルダーがあった場合

>>> nums = 'what did the number %s say to number %s? Nice belt!!'
>>> print(nums % (0, 8))
what did the number 0 say to number 8? Nice belt!!

複数のプレースホルダーを使うときは、置き換えるデータ「0, 8」をカッコで囲みます。
先頭の「0」から順番にプレースホルダーに埋め込まれます。

文字列の掛け算

>>> print('a' * 10 )
aaaaaaaaaa

文字列に掛け算をすることも可能です。’a’に10をかけると、’aaaaaaaaa’になります。

トラックバック用のURL
プロフィール

名前:イワサキ ユウタ 職業:システムエンジニア、ウェブマスター、フロントエンドエンジニア 誕生:1986年生まれ 出身:静岡県 特技:ウッドベース 略歴 20

最近の投稿
人気記事
カテゴリー
広告