最終更新:2021-08-13 (金) 16:30:48 (1005d)  

Python 2/文字列
Top / Python 2 / 文字列

  • 文字列にはstr型とunicode型がある。日本語を使う場合はunicode型を使うこと。
  • r="abc"*3
    print r 
    #abcabcabc
    
    m="""Hello
    World."""
    print m 
    
    print u"ほげ"

メモ

  • Pythonの文字列はimmutable

組み込み型

モジュール

クォート

#トリプルクォートまである
 '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進表記
    %cACII 1文字
    %rreprで得られる文字列
    %sstrで得られる文字列
    %%%

f

関連