モーダルを閉じる工作HardwareHub ロゴ画像

工作HardwareHubは、ロボット工作や電子工作に関する情報やモノが行き交うコミュニティサイトです。さらに詳しく

利用規約プライバシーポリシー に同意したうえでログインしてください。

工作HardwareHub ロゴ画像 (Laptop端末利用時)
工作HardwareHub ロゴ画像 (Mobile端末利用時)
目次目次を開く/閉じる

Python 文字列操作のコードスニペット

モーダルを閉じる

ステッカーを選択してください

モーダルを閉じる

お支払い内容をご確認ください

購入商品
」ステッカーの表示権
メッセージ
料金
(税込)
決済方法
GooglePayマーク
決済プラットフォーム
確認事項

利用規約をご確認のうえお支払いください

※カード情報はGoogleアカウント内に保存されます。本サイトやStripeには保存されません

※記事の執筆者は購入者のユーザー名を知ることができます

※購入後のキャンセルはできません

作成日作成日
2013/07/21
最終更新最終更新
2022/01/22
記事区分記事区分
一般公開

目次

    アカウント プロフィール画像 (サイドバー)

    プログラミング教育者。ScratchやPythonを教えています。

    0
    ステッカーを贈るとは?

    RubyやPerlなどの文字列と概ね同じ感覚で扱えますが、細かい点では様々な違いがあります。
    例えば、シングルクォーテーションであってもエスケープシーケンスが使用できます。

    sample.py

    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    
    print 'line1\nline2' # シングルクォーテーションであってもエスケープシーケンスが有効
    print r'line1\nline2' # 'r'を付ける (Raw文字列化) ことで無効化可能 (Perlのシングルクォーテーション化)
    

    実行例

    $ python sample.py 
    line1
    line2
    line1\nline2
    

    トリプルクォーテーション

    ダブルクォーテーションまたはシングルクォーテーションを三つ並べることで、他の言語でいうところのヒアドキュメントのような、複数行に渡る文字列を記述できます。

    sample.py

    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    
    docstr = """
    Here is some documents describing
    the usage of this function.
    """
    print docstr
    

    出力例

    $ python sample.py 
    
    Here is some documents describing
    the usage of this function.
    

    スライシング

    シーケンスの一部を切り出します。C言語などのfor文と対応付けて考えると理解がしやすいかもしれません。

    sample.py

    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    
    string = "This is a string."
    
    print string[:4] # for(int i=0; i<4; ++i)
    print string[:-1] # for(int i=0; i<string.size()-1; ++i)
    print string[1:4] # for(int i=1; i<4; ++i)
    print string[1:] # for(int i=1; i<string.size(); ++i)
    
    print string[1::2] # for(int i=1; i<string.size(); i+=2)
    print string[::2] # for(int i=0; i<string.size(); i+=2)
    
    print string[3:0:-1] # for(int i=3; i>0; --i)
    print string[::-1] # for(int i=string.size()-1; i>=0; --i)
    

    出力例

    $ python sample.py 
    This
    This is a string
    his
    his is a string.
    hsi  tig
    Ti sasrn.
    sih
    .gnirts a si sihT
    

    文字列と数値の変換方法

    sample.py

    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    
    x = 123
    y = "123"
    print x + int(y)
    print x + float(y)
    print str(x) + y
    

    出力例

    $ python sample.py 
    246
    246.0
    123123
    

    不変性

    Pythonの文字列はPerlやRubyと異なり変更ができません。replaceメソッドを用いるなどして、新たな文字列オブジェクトを生成することで対処します。

    sample.py

    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    
    s = "This is a string."
    
    # s[0] = 't'    # エラー
    s = s.replace('This', 'this')
    
    print s
    

    出力例

    $ python sample.py 
    this is a string.
    

    書式指定文字列

    C言語などのsprintfに相当する記述もできます。

    sample.py

    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    
    print "%d + %d = %d, %s" % (1, 1, 2, 'is this ok?')
    
    # ディクショナリを使用した例
    print "%(val1)d + %(val1)d = %(val2)d, %(str)s" % {'val1':1, 'val2':2, 'str':'is this ok?'}
    

    出力例

    $ python sample.py 
    1 + 1 = 2, is this ok?
    1 + 1 = 2, is this ok?
    

    Python 2.6 からは format 関数が利用できます

    In [9]: '{} + {} = {}'.format(1.0, 1, '2?')
    Out[9]: '1.0 + 1 = 2?'
    
    In [10]: '{myfloat} + {myint} = {mystr}'.format(myfloat=1.0, myint=1, mystr='2?')
    Out[10]: '1.0 + 1 = 2?'
    

    文字列に関する関数

    join

    print '-'.join("string")
    

    出力例

    s-t-r-i-n-g
    

    find

    print "This is a string".find('his')
    

    出力例

    1
    

    split

    print "This is a string".split()  # デフォルトでは空白で区切る
    print "This,is,a,string".split(',')
    

    出力例

    ['This', 'is', 'a', 'string']
    ['This', 'is', 'a', 'string']
    

    upper, lower

    print "This is a string.".upper()
    print "This is a string.".lower()
    

    出力例

    THIS IS A STRING.
    this is a string.
    

    rstrip, lstrip, strip

    print len(" 123   \n".rstrip())  # right strip
    print len(" 123   \n".strip())
    

    出力例

    4
    3
    

    開始文字列または終了文字列による判定

    'abc'.startswith('ab')
    'abc'.endswith('bc')
    

    正規表現

    pythonで正規表現を使用するためには、reモジュールをインポートする必要があります。

    sample.py

    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    
    from re import compile as regexcompile
    
    prog = regexcompile('/(.*)/(.*)/(.*)')
    match = prog.match('/usr/bin/python')
    for i in range(1,4):
        print match.group(i)
    print match.groups()
    

    出力例

    $ python sample.py 
    usr
    bin
    python
    ('usr', 'bin', 'python')
    

    文字列が含まれているかの確認 (in)

    In [3]: 'aaa' in 'xxxaaaxxx'
    Out[3]: True
    
    0
    詳細設定を開く/閉じる
    アカウント プロフィール画像 (本文下)

    プログラミング教育者。ScratchやPythonを教えています。

    記事の執筆者にステッカーを贈る

    有益な情報に対するお礼として、またはコメント欄における質問への返答に対するお礼として、 記事の読者は、執筆者に有料のステッカーを贈ることができます。

    さらに詳しく →
    ステッカーを贈る コンセプト画像

    Feedbacks

    Feedbacks コンセプト画像

      ログインするとコメントを投稿できます。

      関連記事