











基本
文字列の記述方法
数値は整数、浮動小数点ともに、直接数値を記述していましたが、文字列の場合、’ シングルクォーテーションまたは ” ダブルクォーテーションでくくった部分が文字列として認識されます。これにより、変数や関数と文字列を区別します。
変数に格納した文字列は数値と同じように print 関数などで出力できます。
s = 'Hello, Python!' #シングルクォーテーション
t = "Hello, Python!" #ダブルクォーテーション
print(s)
print(t)
結果:
Hello, Python!
Hello, Python!
2種類の記法の意味とエスケープ文字
Python において、シングルクォーテーションとダブルクォーテーションに意味上の区別はありません。ただ、2種類ある意義としては、例えば、
I'm a Python user!
という1文を文字列にしたいとします。この時、
h = 'I'm a Python user!'
としてしまうと、’I’ の部分で文字列が終わったと見なされてしまい、文法エラーとなります。このとき
h = "I'm a Python user!"
とすれば、ダブルクォーテーションで文字列が始まっているので、シングルクォーテーションは文字列の一部だと Python も理解でき、文法エラーとなりません。
もう一つの対処方法として、 \ (バックスラッシュ・円記号)によるエスケープがあります。
h = 'I\'m a Python user!'
print(h)
このように記述すると、\ バックスラッシュの後の シングルクォーテーションは「特別な意味を持たないただの文字ですよ」と Python に伝えることになります。
結果:
I'm a Python user!
これはシングルクォーテーションではなく、ダブルクォーテーション・他の特殊文字でも使えます。例えば、バックスラッシュ記号自体を出力した場合は、 \\ と2個続けて記述することで、 \ 記号を文字列の中に含めることができます。
h = ‘The price of this pen is \\100’
結果
The price of this pen is \100
文字列の演算
例えば、 print で複数の変数を表示したいとき、定数の文字列と同時に表示したいときには以下のように記述していました。
s = 'This is string'
print('s:', s)
結果:
s: This is string
これは、以下のように + 加算で表現することもできます。
print('s:' + ' ' + s) #printにコンマ区切りで値を入れると、半角スペースが追加される
また、もちろん変数に代入することもできます。
s = 's: ' + s
print(s)
結果:
s: This is string
数値型との結合
price = 100
s = 'The price of this pen is \\'
print(s + str(price)) #str() を使わないとエラー!
結果:
The price of this pen is \100
str() は、文字列型に変換(キャスト)する関数です。
print(type(price))
print(type(str(price)))
結果:
<class 'int'>
<class 'str'>
数値として計算
s = '110'
print(price + int(s))
結果:
210
float 型を int 型に変換したように、文字列型 str も、中身が数字であれば int型、float型にキャストして数値演算が可能です。
文字列の切り出し・スライス
文字列の一部分だけを切り出すことを、スライスと言います。
h = "I'm a Python user!"
print(h[0])
結果:
I
これは、文字列 h の一番最初の文字(プログラミングでは通常、最初は 0 から数えます)だけを切り出して printで表示するという意味です。また、 0 の部分を添え字やインデックスと呼びます。
複数の文字を切り出したい場合には、インデックスを : で区切って入力します。
print[h[0:3]] #1文字目から3文字目までを表示する
結果:
I'm
1+3で4文字目まで表示されるのでは? と思うかもしれません。そういうときには、エディタのキャレットをイメージしてください。0の時は、1文字目の前にキャレットがあり、3の時は、4文字目の前、3文字目の後ろにキャレットがあります。ここの間を選択すると、1~3文字目が選択されます。
また、先頭からの場合、最初の0を省略することができ、先ほどのprintは
print(h[:3])
と記述することもできます。また、最後までを省略することもできます。
print(h[3:])
結果:
a Python user!
今度は、4文字目の半角スペースから出力が始まっている点も注目です。
文字列の後ろからスライス
文字列が何文字あるか分からないけど、最後の1文字目が欲しい場合もあります。文字列の数を数えるlen関数というものもありますが、今回は添え字・インデックスのみで対応してみます。
print(h[-1])
結果:
!
また、 -1 だけでなく、後ろからの文字数を使うことができます。
print(h[-5:])
結果:
user!
これを、以下のようにしてしまうと、先ほど説明したキャレットの法則に基づいて意図しない結果になってしまうかもしれません
print(h[-5:-1]) #最後の文字の手前にカーソルがくる
結果:
user
スライスした文字列の加工
例えば、文字列の最後の一文字を、!から、.ピリオドに変更したいとします。
h[-1] = '.' #エラー!
上記のように、文字列の一部を入れ換える計算はできません。そこで、以下のようにします。
h = h[:-1] + '.' #最後の文字手前までを切り出して、 . とつなげる
print(h)
結果:
I'm a Python user.











