Pythonプログラミングで

文字列のメモ

目次

イミュータブルについて

試しに下のコードを動かしてみてください。

                    
s = 'abcdefg'
s[2] = 'x'
print(s)
                    
                

'abcdefg' という文字列の 3 文字目を 'x' に変えようと思ってこのコードを書いたのですが、エラーが出てこんな表示が出てくると思います。

'str' object does not support item assignment

つまりは「str 型である s はその中身を変えることはできない」ってことが言いたいんです。これを「str 型はイミュータブルである」というふうに言います。だからもしこの文字列の 3 文字目を 'x' にしたいなら、後に出てくる replace メソッドなりなんなりを使わなければなりません。

str 型がイミュータブルだということは結構様々な場面でお世話になると思いますので、是非頭に叩き込んでおいてください。

各種メソッド

upper()

すべての文字を大文字にして文字列を返す。

print('Hello, World!'.upper())

HELLO, WORLD!

lower()

すべての文字を小文字にして文字列を返す。

print('Hello, World!'.lower())

hello, world!

isupper()

1 文字以上のすべてのアルファベットが大文字なら True, それ以外では False をリターンする。

                    
print('Hello'.isupper())
print('WORLD!'.isupper())
print('123'.isupper())
                    
                
                    
False
True
False
                    
                

islower()

1 文字以上のアルファベットがすべて小文字なら True, そうでなければ False をリターンする。

                    
print('hello,'.islower())
print('World!'.islower())
print('123'.islower())
                    
                
                    
True
False
False
                    
                

isalpha()

1 文字以上のアルファベットのみで構成されていれば True, それ以外は False をリターン。

                    
print('Hello'.isalpha())
print('World!'.isalpha())
                    
                
                    
True
False
                    
                

isalnum()

1 文字以上のアルファベットか数字から構成されていれば True

                    
print('1Hello'.isalnum())
print('World!'.isalnum())
print(' guys'.isalnum())
                    
                
                    
True
False
False
                    
                

isdecimal()

1 文字以上の数字のみから構成されていれば True

                    
print('123'.isdecimal())
print('7days'.isdecimal())
print('5!'.isdecimal())
                    
                
                    
True
False
False
                    
                

isspace()

スペース、タブ、改行のいずれかのみで構成されていれば True

                    
print(' \t\n'.isspace())
print(' \n'.isspace())  # 全角スペース + 改行
print('1\t'.isspace())
                    
                
                    
True
True
False
                    
                

istitle()

大文字始まりで他がすべて小文字の英単語から構成されていれば True

                    
print('Hello World'.istitle())
print('Hello, World!'.istitle())
print("It's New World Order".istitle())
print('It is New World Order'.istitle())
                    
                
                    
True
True
False
False
                    
                

startswith()

引数の文字列から始まれば True

                    
print('Hello, world!'.startswith('Hello'))
print('Hello, world!'.startswith('Hell'))
print('Hello, world!'.startswith('Hello, world!'))
print('Hello, world!'.startswith('hello'))
                    
                
                    
True
True
True
False
                    
                

endswith()

引数の文字列で終われば True

                    
print('Hello, world!'.endswith('world!'))
print('Hello, world!'.endswith('orld!'))
print('Hello, world!'.endswith('world'))
print('Hello, world!'.endswith('World!'))
                    
                
                    
True
True
False
False
                    
                

join()

引数の文字列のリストを一つに連結してリターンする。

                    
print(', '.join(['dogs', 'cats', 'hamsters']))
print(' and '.join(['dogs', 'cats', 'hamsters']))
                    
                
                    
dogs, cats, hamsters
dogs and cats and hamsters
                    
                

split()

文字列を分割してリスト化したものをリターンする。

                    
print('I love NY'.split())
print('I love NY'.split('lo'))
spam = '''Paul, called to be an apostle of Christ Jesus by the will of God, and our brother Sosthenes, 

To the chrch of God in Corinth, to those sanctified in Christ Jesus and called to be his holy people, together with all those everywhere who call on the name of our Lord Jesus Christ—their Lord and ours:

Grace and peace to you from God our Father and the Lord Jesus Christ. '''   # Corinthians 1
print(spam.split('\n'))
                    
                
                    
['I', 'love', 'NY']
['I ', 've NY']
['Paul, called to be an apostle of Christ Jesus by the will of God, and our brother Sosthenes, ', '', 'To the chrch of God in Corinth, to those sanctified in Christ Jesus and called to be his holy people, together with all those everywhere who call on the name of our Lord Jesus Christ—their Lord and ours:', '', 'Grace and peace to you from God our Father and the Lord Jesus Christ. ']
                    
                

ljust()

引数の文字数内で左に寄せてリターンする。

print('O Romeo, Romeo,'.ljust(20) + 'wherefore art thou Romeo')

O Romeo, Romeo, wherefore art thou Romeo

rjust()

引数の文字数内で右に寄せてリターンする。

print('O Romeo, Romeo, wherefore art thou Romeo'.rjust(50))

O Romeo, Romeo, wherefore art thou Romeo

center()

引数の文字数内で中央に寄せてリターンする。

print('O Romeo, Romeo, wherefore art thou Romeo'.center(50) + '?')

O Romeo, Romeo, wherefore art thou Romeo ?

strip()

引数の文字列を両端から削除し続けてリターンする。デフォルトは空白・改行・タブ文字。

                    
print("   ...... Who's there!? ... \n".strip())
print('KabaddiKabaddiKabaddiTouchKabaddiCatchingKabbadi'.strip('Kabaddi'))
                    
                
                    
...... Who's there!? ...
TouchKabaddiCatching
                    
                

lstrip()

文字列左側から引数の文字列を削除し続ける。デフォルトは空白文字。

                    
print("   ...... Who's there!? ... \n".lstrip())
print('KabaddiKabaddiKabaddiTouchKabaddiCatchingKabbadi'.lstrip('Kabaddi'))
                    
                
                    
...... Who's there!? ... 

TouchKabaddiCatchingKabbadi
                    
                

rstrip()

文字列右側から引数の文字列を削除し続ける。デフォルトは空白文字。

                    
print("   ...... Who's there!? ... \n".rstrip())
print('KabaddiKabaddiKabaddiTouchKabaddiCatchingKabbadi'.rstrip('Kabaddi'))
                    
                
                    
...... Who's there!? ...
KabaddiKabaddiKabaddiTouchKabaddiCatching 
                    
                

replace()

第 1 引数の文字列を第 2 引数の文字列に置き換えてリターンする。

print('Do not enter while I am sleeping! Do not!'.replace('not', 'please'))

Do please enter while I am sleeping! Do please!