文字列操作、演算
Pythonには文字列操作、演算について様々な演算が用意されています。
以下によく使いそうなもののサンプルをピックアップして、コードにしてみました。
msg = 'Hello, Python' # 文字列の長さを取得する msg_length = len(msg) # 13と取得できる print 'len : ' + str(msg_length) # findメソッド py_idx_of_msg = msg.find('Py') # 7と取得できる。Pyのある場所のインデクス print 'msg.find : ' + str(py_idx_of_msg) # 文字列インデクシング c = msg[7] print 'msg[7] : ' + c #'P'と出力 # 文字列のスライシング msg2 = msg[7:9] print 'msg[7:9] : ' + msg2 # 'Py'と出力 # 特定の文字列がある文字列中に入っているかの確認 if 'Py' in msg : print "'Py' in msg is true" # 文字列から1文字ずつ取得する for c in msg: print 'c : ' + c # 文字列置換 msg3 = msg.replace('Hello', 'Hola') print msg3 # Hola, Pythonと出力 # 文字列分割してリストに。 splitted_word = msg.split(',') print splitted_word # ['Hello', ' Python'] と出力 # 文字列を再連結 joined_word = ','.join(splitted_word) print joined_word # Hello, Pythonと出力
一応、これくらいあれば、基本的な文字列操作はできると思いますが、今後は必要に応じて追加していきます。