文字列
入門編では実行方法と基礎構文を学びました。 基礎編ではまず文字列について解説します。
Pythonの文字列は 「'」(シングルクォーテーション)と「"」(ダブルクォーテーション)の両方で表現出来ます。
# -*- coding: utf-8 -*- print 'python-izm' print "python-izm"
--実行結果--
python-izm python-izm
クォート記号3つで複数行に分けて書く事も出来ます。
# -*- coding: utf-8 -*- test_str = """ test_1 test_2 """ print test_str
--実行結果--
test_1 test_2
文字列の連結は「 + 」を使います。
# -*- coding: utf-8 -*- test_str = 'python' test_str = test_str + '-' test_str = test_str + 'izm' print test_str
--実行結果--
python-izm
文字列への追加も可能です。
# -*- coding: utf-8 -*- test_str = '012' test_str += '345' test_str += '678' test_str += '9' print test_str
--実行結果--
0123456789
「 * 」を用いることで指定回数分繰り返すこともできます。
# -*- coding: utf-8 -*- test_str = '012' * 3 print test_str
--実行結果--
012012012
文字列への変換は「str」を使用します。
# -*- coding: utf-8 -*- test_integer = 100 print str(test_integer) + '円'
--実行結果--
100円
文字列の置換は「replace」を使用します。
# -*- coding: utf-8 -*-
test_str = 'python-izm'
print test_str.replace('izm', 'ism')
--実行結果--
python-ism
文字列の分割は「split」を使用します。 これはリスト(list)という形で戻り値を返しますが、リストについては入門編の後の項で説明します。※戻り値とは関数などが返す結果のことで、様々な形で返されます。戻り値を返さないものもあります。
# -*- coding: utf-8 -*-
test_str = 'python-izm'
print test_str.split('-')
--実行結果--
['python', 'izm']
文字列の左に値を埋める場合は「rjust」を使います。 第一引数が埋めた後の桁数、第二引数が埋め込む文字列です。 ゼロ以外の文字列も埋め込み可能です。
# -*- coding: utf-8 -*- test_str = '1234' print test_str.rjust(10, '0') print test_str.rjust(10, '!')
--実行結果--
0000001234 !!!!!!1234
特定の文字列を指定せずゼロで桁埋めする場合は「zfill」を使います。
# -*- coding: utf-8 -*- test_str = '1234' print test_str.zfill(10) print test_str.zfill(3)
--実行結果--
0000001234 1234
文字列の検索方法は様々です。 まずは文字列の先頭が任意の文字であるかを調べます。 戻り値はTrueもしくはFalseです。※TrueやFalseは真偽値を表します。簡単にいうと〇か×かということで〇はTrue、×はFalseになります。
# -*- coding: utf-8 -*-
test_str = 'python-izm'
print test_str.startswith('python')
print test_str.startswith('izm')
--実行結果--
True False
次は文字列中に任意の文字が含まれているかを調べます。 戻り値は同じくTrueかFalseです。
# -*- coding: utf-8 -*- test_str = 'python-izm' print 'z' in test_str print 's' in test_str
--実行結果--
True False
指定の文字列を大文字・小文字へ変換するには「upper」もしくは「lower」を使います。
# -*- coding: utf-8 -*- test_str = 'Python-Izm.Com' print test_str.upper() print test_str.lower()
--実行結果--
PYTHON-IZM.COM python-izm.com
文字列の先頭・末尾を削除した値を取得します。 それぞれ「lstrip」は先頭(左から)、「rstrip」は末尾(右から)の削除となり、引数なしでは空白を除去します。 ※末尾の空白の削除は出力結果ではわかりづらいので、スラッシュを付加しています。
# -*- coding: utf-8 -*-
print '----------------------------------'
test_str = ' python-izm.com'
print test_str
test_str = test_str.lstrip()
print test_str
test_str = test_str.lstrip('python')
print test_str
print '----------------------------------'
test_str = 'python-izm.com '
print test_str + '/'
test_str = test_str.rstrip()
print test_str + '/'
test_str = test_str.rstrip("com")
print test_str
--実行結果--
----------------------------------
python-izm.com
python-izm.com
-izm.com
----------------------------------
python-izm.com /
python-izm.com/
python-izm.
以上で文字列の解説は終了です。次は数値です!
