Pythonを学ぶ その5

テキストを生成する方法
text1 = 'hello python'

text2 = '''hello
world
python'''

print('hello' + 'world')
print('hello + str(5)')

文字列にテキストや数字を埋め込む

>>> 'hello {}{}'.format('python',5)
'hello python5'
>>> 'hello {}  {}'.format('python', 5)
'hello python  5'
>>> print('5'.zfill(6))
000005
>>> print(str(101).zfill(5))
00101
>>> print('hello {0:05d} world'.format(5))
hello 00005 world
>>> print('escape sample1 \.')
escape sample1 \.
>>> print('escape sample1 \'.')
escape sample1 '.
>>> print('escape sample1 \a.')
escape sample1 .
>>> print('escape sample1 \\.')
escape sample1 \.

テキストを加工する

文字の取得 リストと同じように マイナスにすると後ろから数えた文字列を [x:y]でx番目より後ろ、y番目より前を取得

>>> print(text[4])
o
>>> print(text[100])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> print(text[-4])
t
>>> print(text[6:])
world python
>>> print(text[:11])
hello world
>>> print(text[:])
hello world python
>>> print(text[6:11])
world

文字列.replace(x,y)xをyに置き換え

検索1:存在の確認 検索2:位置の確認

>>> 'wor' in text
True
>>> 'heli' in text
False
>>> text.find('wor')
6
>>> text.find('heli')
-1
>>> text.find('o')
4

findはマッチしたものの一番左にあるものの位置を返す rfindは右

strip split

text = '''1,taro,35,male
2,jiro,29,male
3,hanako,23,female'''
print('thank n you')

for line in text.split('\n'):
    elems = line.split(',')
    print('{} {}'.format(elems[1].strip(),elems[2].strip()))

特定の文字列で結合

>>> p = ['1','taro','36','male']
>>> ','.join(p)
'1,taro,36,male'
>>> p
['1', 'taro', '36', 'male']
ファイル処理

プログラムがどのようにファイルを扱うかは、OSの仕組みに基づいているため多くのプログラミング言語でさほど変わりません

  1. ファイルを指定
  2. ファイルをオープン
  3. 読み書き
  4. ファイルをクローズ
読み書きの処理

テキストファイルは行ごとに処理 バイナリファイルは先頭から何バイト目かを指定して処理

f = open('text.txt','r')
print(type(f))

for line in f:
    print('hello' + line)

f.close()

printの改行をなくすには後ろに, 丸ごと読み込み、文字列として取得するread

f = open('text.txt','r')
text = f.read()
print(text)

lines = text.split('\n')
print(lines)

f.close()

ファイルに書き込み(上書き)

f = open('text.txt','w')
f.write('123')
f.write('456')
f.close()

追記する必要ある時は、モードをaにする

ディスクへの書き込みを強制的に行いたい場合(closeのタイミングで必ず書き込まれるが途中でやりたいのなら)flush()関数

Pickle

Pythonのデータをファイルに保存し、読み取って復元する

import pickle
a = {'hello':1,'world':[1,2,3]}
f1 = open('test.dump','wb')
pickle.dump(a,f1)
f1.close()

f2 = open('test.dump','rb')
b = pickle.load(f2)
f2.close()
print(b)

そういえば、 split関数は、text.split()みたいに、textを対象にすることができる。 こういう形で関数の前に文字列.をつけられるようにするにはどうすれば良いのだ? 普通に引数として渡せば良いのだけど。

今日はここまで