目次
プログラミング教育者。ScratchやPythonを教えています。
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
記事の執筆者にステッカーを贈る
有益な情報に対するお礼として、またはコメント欄における質問への返答に対するお礼として、 記事の読者は、執筆者に有料のステッカーを贈ることができます。
さらに詳しく →Feedbacks
ログインするとコメントを投稿できます。
関連記事
- Python コードスニペット (条件分岐)if-elif-else sample.py #!/usr/bin/python # -*- coding: utf-8 -*- # コメント内であっても、ASCII外の文字が含まれる場合はエンコーディング情報が必須 x = 1 # 一行スタイル if x==0: print 'a' # 参考: and,or,notが使用可能 (&&,||はエラー) elif x==1: p...
- Python コードスニペット (リスト、タプル、ディクショナリ)リスト range 「0から10まで」といった範囲をリスト形式で生成します。 sample.py print range(10) # for(int i=0; i<10; ++i) ← C言語などのfor文と比較 print range(5,10) # for(int i=5; i<10; ++i) print range(5,10,2) # for(int i=5; i<10;...
- ZeroMQ (zmq) の Python サンプルコードZeroMQ を Python から利用する場合のサンプルコードを記載します。 Fixing the World To fix the world, we needed to do two things. One, to solve the general problem of "how to connect any code to any code, anywhere". Two, to wra...
- Matplotlib/SciPy/pandas/NumPy サンプルコードPython で数学的なことを試すときに利用される Matplotlib/SciPy/pandas/NumPy についてサンプルコードを記載します。 Matplotlib SciPy pandas [NumPy](https://www.numpy
- pytest の基本的な使い方pytest の基本的な使い方を記載します。 適宜参照するための公式ドキュメントページ Full pytest documentation API Reference インストール 適当なパッケージ