最終更新:2021-08-13 (金) 16:30:48 (958d)
Python 2/文字列
r="abc"*3 print r #abcabcabc m="""Hello World.""" print m print u"ほげ"
メモ
- Pythonの文字列はimmutable
組み込み型
- Python 2/str:何らかの形式でエンコードされた文字
- Python 2/unicode
モジュール
クォート
#トリプルクォートまである 'aa' "aa" '''aa''' """aa"""
二種類の型
ASCII文字列 (Python 2/str)
a = "aaa"
Unicode文字列 (Python 2/unicode)
a = u"あうあう"
unicode<->str
unichr(unicode) str = uninocde.encode('shift_jis') unicode = str.decode('utf-8')
演算
- + - 連結
- * - 反復
- += - 連結
関数
大文字・小文字
str.lower() str.upper() str.swapcase() str.capitalize() #先頭文字を大文字に str.title() #単語の先頭を大文字に
検索
str.find(needle) #検索してインデックスを返す str.rfind(needle) #インデックスを返す #見つからない場合は-1 str.index(needle) #検索してインデックスを返す str.rindex(needle) #インデックスを返す #見つからない場合はエラー str.count(needle) - 出現回数
開始・終了文字列
str.startswith(needle) #True/False str.endswith(needle) #True/False
置換
str.replace(search,replace)
リストとの相互変換
list = str.split(' ') str = ' '.join(list)
前後の空白
str.strip() str.center(strwidth) str.lstrip() str.rstrip() str.ljust(strwidth) str.rjust(strwidth)
文字種
str.isalpha() str.isdigit() str.isalnum() str.isspace() str.isupper() str.islower() str.istitle()
比較
- 文字列の比較は、文字列を構成する1つ1つの文字の文字コードを順番に比較していき、最初に大小の判定がついた時点で、その大小が文字列全体の大小になる
- 最後まで調べて大小の判断がつかなかった場合は長いほうが大きいとする
%
- sprintfみたいに使える
last = 'yamada' first = 'taro' print 'my name is %s %s' % (last,first) #my name is yamada taro
変数指示子?
%d,%i 整数10進数表記 %u 符号なし整数10進数表記 %f,%F 浮動小数点小数表記 %e,%E 浮動小数点指数表記 %g,%G 浮動小数点小数表記または指数表記の短い方 %o 整数8進数表記 %x,%X 整数16進表記 %c ACII 1文字 %r reprで得られる文字列 %s strで得られる文字列 %% %