LoginSignup
39
44

More than 3 years have passed since last update.

Python3系の基礎文法(文字列)

Last updated at Posted at 2017-06-25

概要

O'Reilly Japan の「入門 Python 3」を参考に、Python3系の基礎文法を勉強します。
同じようにPythonを勉強したいと思ってる方の参考になれば幸いです。

Pythonの文字列について

文字列はイミュータブル(後から値を変更できない)なので、文字列を書き換えることはできない。
例えば、ABCの先頭文字をGに変更する場合、下記のような方法を試みるとエラーになる。

>>> target = 'ABC'
>>> target[0] = 'G'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

書き換えたい場合、関数を使う等を行い新しい文字列として操作結果を取得する。

文字列の作成・抽出

文字列の作成

>>> # シングルクォートを使う場合
>>> 'sample'
'sample'

>>> # ダブルクォートを使う場合
>>> "sample"
'sample'

>>> # シングルクォート(3個)
>>> '''sample'''
'sample'

>>> # ダブルクォート(3個)
>>> """sample"""
'sample'

>>> # 空文字
>>> ''
''

文字の連結

>>> # リテラル文字列の連結
>>> 'ABC' + 'DEF'
'ABCDEF'

>>> # リテラル文字列の場合、並べるだけでも連結できる
>>> 'ABC' 'DEF'
'ABCDEF'

>>> # 文字列変数の連結
>>> target1 = 'ABC'
>>> target2 = 'DEF'
>>> target1 + target2
'ABCDEF'

>>> # 文字列変数の場合、並べただけだとエラーになる
>>> target1 = 'ABC'
>>> target2 = 'DEF'
>>> target1 target2
  File "<stdin>", line 1
    target1 target2
                  ^
SyntaxError: invalid syntax

文字列の繰り返し

>>> 'pyon ' * 5
'pyon pyon pyon pyon pyon '

文字列から特定文字を取り出す

>>> target = 'ABC'
>>> target[0]
'A'
>>> target[1]
'B'
>>> target[2]
'C'

スライス

スライスを使うと、文字列から部分文字列を取り出すことができる。

# [start:end:step]
#   start :先頭オフセット
#   end   :末尾オフセット
#   step  :ステップ(何文字ごとか)

>>> target = 'ABCDEFGHIJKLMN'

>>> # 文字列全体を取得
>>> target[:]
'ABCDEFGHIJKLMN'

>>> # オフセット5から末尾まで
>>> target[5:]
'FGHIJKLMN'

>>> # オフセット2から5
>>> target[2:5]
'CDE'

>>> # 最後の3文字
>>> target[-3:]
'LMN'

>>> # オフセット0から10までを2ステップごとに
>>> target[0:10:2]
'ACEGI'
>>> # このように省略することもできる
>>> target[:10:2]
'ACEGI'

関数による操作

str()による型変換

>>> str(123)
'123'
>>> str(True)
'True'

replace()による置換

>>> target = 'ABC'
>>> target.replace('A','G')
'GBC'

len()による長さの取得

>>> target = 'ABCDE'
>>> len(target)
5

split()による分割

>>> # セパレータにカンマを指定
>>> target = 'AB,C,DE,F'
>>> target.split(',')
['AB', 'C', 'DE', 'F']

>>> # セパレータを指定しない場合、空白文字(改行、スペース、タブ)をセパレータとして扱う
>>> target = 'A B C DE F'
>>> target.split()
['A', 'B', 'C', 'DE', 'F']

join()による結合

join()関数は、split()関数の逆

>>> # 区切り文字を指定してから、リストを指定
>>> str_list = ['AB', 'C', 'DE', 'F']
>>> target = ','.join(str_list)
>>> print(target)
AB,C,DE,F

startswith()による先頭文字判定

>>> target = 'ABCDEFGHIJKLMN'
>>> target.startswith('ABC')
True
>>> target.startswith('BCD')
False

endswith()による先頭文字判定

>>> target = 'ABCDEFGHIJKLMN'
>>> target.endswith('LMN')
True
>>> target.endswith('KLM')
False

find()によるオフセット取得

>>> # 見つかる場合
>>> target = 'ABCDEFGHIJKLMN'
>>> target.find('D')
3
>>> target.find('DE')
3
>>> # 見つからない場合、-1が返される
>>> target.find('DG')
-1
>>> target.find('T')
-1

count()による件数カウント

>>> target = 'AABBBCAAABCCCCCC'
>>> target.count('A')
5
>>> target.count('B')
4
>>> target.count('C')
7
>>> target.count('AA')
2
>>> target.count('D')
0

大文字、小文字の変更

capitalize()で先頭文字だけ大文字に変更

>>> target = 'thank you for coming.'
>>> target.capitalize()
'Thank you for coming.'

title()で全ての単語をタイトルケースに変更

>>> target = 'thank you for coming.'
>>> target.title()
'Thank You For Coming.'

upper()で全ての文字を大文字に変更

>>> target = 'thank you for coming.'
>>> target.upper()
'THANK YOU FOR COMING.'

lower()で全ての文字を小文字に変更

>>> target = 'THANK YOU FOR COMING.'
>>> target.lower()
'thank you for coming.'

swapcase()で大文字小文字を逆にする

>>> target = 'AbcdEFg'
>>> target.swapcase()
'aBCDefG'

文字の配置

center()で中央配置

>>> #スペース40の中で中央配置
>>> target = 'thank you for coming.'
>>> target.center(40)
'         thank you for coming.          '

ljust()で左端配置

>>> #スペース40の中で左端配置
>>> target = 'thank you for coming.'
>>> target.ljust(40)
'thank you for coming.                   '

rjust()で右端配置

>>> target = 'thank you for coming.'
>>> target.rjust(40)
'                   thank you for coming.'

その他の文字列関数が知りたくなったら

文字列関数の標準ドキュメント
http://bit.ly/py-docs-strings

39
44
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
39
44