Szarny.io

There should be one-- and preferably only one --obvious way to do it.

Python3メモ - 文字列関連

 Python3の忘れそうな文字列関連のメソッド等々についてのメモ

  • string.find(word)
    string内において,最初にwordが出現する位置を返す
    >>> alphabet = "abcdefghijklmnopqrstuvwxyz"
    >>> alphabet.find("k")
    10

  • string.replace(str1, str2, time)
    string内のstr1をstr2へ最大time回置換する
    >>> greeting = "Good Morning, Good Evening, Good Night"
    >>> greeting.replace("Good", "Bad", 2)
    'Bad Morning, Bad Evening, Good Night'


  • string内の一部を変更する
    stringはimmutableなオブジェクトなので,直接変更はできない

    >>> text = "Hello morld"
    >>> text[6] = "w"
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: 'str' object does not support item assignment

  • 解決法1 : listに一旦変換して変更する
    >>> text = "Hello morld"
    >>> text_list = list(text)
    >>> text_list[6] = "w"
    >>> text = "".join(text_list)
    >>> text
    'Hello world'
  • 解決法2 : スライスを用いる

    >>> text = "Hello morld"
    >>> text = text[:6] + "w" + text[7:]
    >>> text
    'Hello world'