>>> val1=int(123) >>> type(val1) <class 'int'>
>>> val2=str(123) >>> type(val2) <class 'str'>
>>> 1 is True False >>> 1 == True True
>>> str1="123" >>> str2="123"
>>> id(str1) 4369725008 >>> id(str2) 4369725008
>>> str1 == str2 True >>> str1 is str2 True
>>> list1=[1,2,3] >>> list2=[1,2,3]
>>> id(list1) 4369290088 >>> id(list2) 4369341832
>>> list1 == list2 True >>> list1 is list2 False
>>> type(None) <class 'NoneType'>
>>> type(True) <class 'bool'> >>> type(False) <class 'bool'>
>>> type(1) <class 'int'>
>>> type(1.0) <class 'float'>
>>> import sys >>> sys.float_info sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1) >>> sys.float_info.max 1.7976931348623157e+308
>>> type(1+1j) <class 'complex'>
>>> import sys >>> sys.maxint AttributeError: 'module' object has no attribute 'maxint'
>>> list1=[1,2,3] >>> list1 [1, 2, 3]int だけではなく 文字や list などなんでも詰め込める
>>> list2=[list1,4,5] >>> list2 [[1, 2, 3], 4, 5]
>>> list3=list('abcd')
>>> list3
['a', 'b', 'c', 'd']>>> list4=list((3,5,4)) >>> list4 [3, 5, 4]
>>> list5=list(range(6)) >>> list5 [0, 1, 2, 3, 4, 5]range() 関数は range(開始,終了,ステップ) というようにも指定できる
>>> list6=list(range(3,9,2)) >>> list6 [3, 5, 7]Pytyon2 では、range() は list を返していたが、Python3 では range 型を返す。range 型は、要素を列挙するイテレータ機能を持っているので、list() 関数で list にすることができる。
>>> whoareyou=range(6) >>> type(whoareyou) <class 'range'>
[追加する要素 for 取り出した要素 in リスト if 追加条件]
>>> ['OSX10.' + str(i) for i in range(9)]
['OSX10.0', 'OSX10.1', 'OSX10.2', 'OSX10.3', 'OSX10.4', 'OSX10.5', 'OSX10.6', 'OSX10.7', 'OSX10.8']
>>> [lang for lang in ['python','perl','ruby','plsql','java','c'] if lang.startswith('p')]
['python', 'perl', 'plsql']>>> lst=[1,2,3,4,5,6]
>>> lst[0] 1 >>> lst[1] 2
>>> lst[0:4] [1, 2, 3, 4]
>>> lst[0:4:2] [1, 3]
>>> lst[3:] [4, 5, 6]
>>> lst[:3] [1, 2, 3]
>>> lst[::-1] [6, 5, 4, 3, 2, 1] >>> lst[5:2:-1] [6, 5, 4]
>>> lst=[1,2,3,4,5,6,5,4,3,2,1]
>> 3 in lst True
>>> lst.index(3) 2
>>> lst.index(3,5) 8
>>> lst.index(3,0,5) 2
>>> lst.index(3,5,10) 8
>>> lst.index(99) ValueError: 99 is not in list
>>> lst=[1,2,3,4,5,6,5,4,3,2,1] >>> len(lst) 11
>>> lst=[1,2,3,4,5,6,5,4,3,2,1] >>> lst.count(3) 2 >>> lst.count(6) 1 >>> lst.count(99) 0
>>> lst=[1,2,3,4,5,6,5,4,3,2,1] >>> max(lst) 6 >>> min(lst) 1要素の "値" を返す関数を第二引数に指定できる。(下の例は 3 で割ったあまりを返す無名関数)
>>> max(lst,key=(lambda p : p % 3)) 2 >>> min(lst,key=(lambda p : p % 3)) 3
>>> lst=[1,2,3,4,5,6,5,4,3,2,1] >>> sum(lst) 36
>>> any([False,False,False]) False >>> any([False,False,True]) True >>> any([True,True,True]) True
>>> all([False,False,False]) False >>> all([False,False,True]) False >>> all([True,True,True]) True >>>
>>> lst [1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1] >>> lst[1]=99 >>> lst [1, 99, 3, 4, 5, 6, 5, 4, 3, 2, 1]範囲を指定して置き換える (1:3 で、lst[1]とlst[2] のあった部分にリストを代入)
>>> lst[1:3] = ['a','b','c','d'] >>> lst [1, 'a', 'b', 'c', 'd', 4, 5, 6, 5, 4, 3, 2, 1]
>>> lst=[1,2,3]
>>> lst.append('a')
>>> lst
[1, 2, 3, 'a']
>>> lst.append(['x','y'])
>>> lst
[1, 2, 3, 'a', ['x', 'y']]>>> lst=[1,2,3]
>>> lst.extend('a')
>>> lst
[1, 2, 3, 'a']
>>> lst.extend(['x','y'])
>>> lst
[1, 2, 3, 'a', 'x', 'y']
+演算子でも追加できるが extend のほうが速い>>> lst=[1,2,3] >>> lst.insert(2,'a') >>> lst [1, 2, 'a', 3]
>>> lst=[1,2,3,4,5,6,5,4,3,2,1] >>> lst.remove(3) >>> lst [1, 2, 4, 5, 6, 5, 4, 3, 2, 1] >>> lst.remove(99) ValueError: list.remove(x): x not in list
>>> lst=[1,2,3,4,5,6,5,4,3,2,1] >>> del lst[1] >>> lst [1, 3, 4, 5, 6, 5, 4, 3, 2, 1]範囲指定 (インデックス 3 と 4 を削除)
>>> lst=[1,2,3,4,5,6,5,4,3,2,1] >>> del lst[3:5] >>> lst [1, 2, 3, 6, 5, 4, 3, 2, 1]範囲指定 (インデックス 3(4),4(5),5(6),6(5),7(4) から ステップ2 で削除 → インデックス 3(4),5(6),7(4) を削除)
>>> lst=[1,2,3,4,5,6,5,4,3,2,1] >>> del lst[3:8:2] >>> lst [1, 2, 3, 5, 5, 3, 2, 1]
>>> lst=['a','ab','abc','abcd'] >>> lst.sort(key=(lambda p : 1.0 / len(p))) >>> lst ['abcd', 'abc', 'ab', 'a']key 関数の値が小さい順に並ぶ。key 関数を省略した場合には値の自然順序にならぶ (整数の場合値の大きさ、文字列の場合辞書順)。
>>> lst=['a','ab','abc','abcd'] >>> lst2=sorted(lst, key=(lambda p : 1.0 / len(p))) >>> lst ['a', 'ab', 'abc', 'abcd'] >>> lst2 ['abcd', 'abc', 'ab', 'a']ソートしたリストをあたらに作って返す。元のリストは変更されない。
>>> lst=['a','ab','abc','abcd'] >>> lst.reverse() >>> lst ['abcd', 'abc', 'ab', 'a']
>>> lst=['a','ab','abc','abcd'] >>> it=reversed(lst) >>> type(it) <class 'list_reverseiterator'> >>> list(it) ['abcd', 'abc', 'ab', 'a']引数の list の順番が反対に返ってくるイテレータを返す。
>>> lst=[1,2,3,4] >>> cpy=lst >>> id(lst) 30364536 >>> id(cpy) 30364536 >>> cpy[1]=99 >>> cpy [1, 99, 3, 4] >>> lst [1, 99, 3, 4]lst と cpy は、同じリストをさす
>>> lst=[1,2,3,['x','y']]
>>> cpy=lst[:]
>>> id(lst)
30364736
>>> id(cpy)
30367496
>>> id(lst[3])
30674696
>>> id(cpy[3])
30674696
>>> cpy[3].append('z')
>>> cpy
[1, 2, 3, ['x', 'y', 'z']]
>>> lst
[1, 2, 3, ['x', 'y', 'z']]
※ cpy=lst[:] と cpy=list(lst) は同じ>>> import copy
>>> lst=[1,2,3,['x','y']]
>>> cpy=copy.deepcopy(lst)
>>> id(lst)
30364536
>>> id(cpy)
30375248
>>> id(lst[3])
30670360
>>> id(cpy[3])
30670200
>>> cpy[3].append('z')
>>> cpy
[1, 2, 3, ['x', 'y', 'z']]
>>> lst
[1, 2, 3, ['x', 'y']]>>> [1,2,3] == [1,2,3] True >>> [1,2,3] != [1,2,3] False
>>> [1,2,3] > [1,3,4] False >>> [1,2,3] < [1,3,4] True >>> [1,2,3] > [1,2] True
>>> [1,2,3] is [1,2,3] False >>> lst=[1,2,3] >>> cpy=lst >>> lst is cpy True
>>> tpl=(1,2,3) >>> tpl (1, 2, 3)
>>> tpl=tuple([4,5,6]) >>> tpl (4, 5, 6)
>>> tpl=(1,2,3) >>> tpl[1] = 99 TypeError: 'tuple' object does not support item assignment
>>> tpl=(1,2,3) >>> del tpl[1] TypeError: 'tuple' object doesn't support item deletion
>>> tpl=(1,2,3) >>> del tpl >>> tpl NameError: name 'tpl' is not defined
>>> tpl=(9,5,6,2,7) >>> sorted(tpl) [2, 5, 6, 7, 9] >>> it=reversed(tpl) >>> type(it) <class 'reversed'> >>> list(it) [7, 2, 6, 5, 9]
>>> set1=set([1,2,3,2,1])
>>> set1
{1, 2, 3}
可変オブジェクトを set の要素に指定することはできない
>>> set3=set([1,2,3,['x','y']]) TypeError: unhashable type: 'list'
Python3 から {} で set を作れるようになった
>>> set2={1,2,3,2,1}
>>> set2
{1, 2, 3}
Python3 からセット内包表記が可能になった
>>> {py + 'thon' for py in ['py','mara','row','py','suxame'] if len(py) < 4}
{'python', 'rowthon'}
>>> {1,2,3} | {2,3,4}
{1, 2, 3, 4}
>>> {1,2,3}.union([2,3,4])
{1, 2, 3, 4}>>> {1,2,3} & {2,3,4}
{2, 3}
>>> {1,2,3}.intersection([2,3,4])
{2, 3}>>> {1,2,3} - {2,3,4}
{1}
>>> {1,2,3}.difference([2,3,4])
{1}>>> {1,2,3} ^ {2,3,4}
{1, 4}
>>> {1,2,3}.symmetric_difference([2,3,4])
{1, 4}>>> for v in {4,8,7,9,2}:
... print(v)
...
8
9
2
4
7>> 3 in {1,2,3}
True>>> set1={1,2,3,4,5,6,5,4,3,2,1}
>>> set1
{1, 2, 3, 4, 5, 6}
>>> len(set1)
6>>> set1={1,2,3}
>>> set1.add(4)
>>> set1
{1, 2, 3, 4}
setは重複が無い集合なので、既にある要素を add() しても元のまま
>>> set1.add(1)
>>> set1
{1, 2, 3, 4}>>> set1={1,2,3}
>>> set1 |= {2,3,4}
>>> set1
{1, 2, 3, 4}
>>> set1={1,2,3}
>>> set1.update([2,3,4])
>>> set1
{1, 2, 3, 4}>>> set1={1,2,3}
>>> set1 &= {2,3,4}
>>> set1
{2, 3}
>>> set1={1,2,3}
>>> set1.intersection_update([2,3,4])
>>> set1
{2, 3}>>> set1={1,2,3}
>>> set1 -= {2,3,4}
>>> set1
{1}
>>> set1={1,2,3}
>>> set1.difference_update([2,3,4])
>>> set1
{1}>>> set1={1,2,3}
>>> set1 ^= {2,3,4}
>>> set1
{1, 4}
>>> set1={1,2,3}
>>> set1.symmetric_difference_update([2,3,4])
>>> set1
{1, 4}>>> set1={1,2,3}
>>> set1.remove(3)
>>> set1
{1, 2}
>>> set1.remove(3)
KeyError: 3
削除対象が無いとエラーが発生する>>> set1={1,2,3}
>>> set1.discard(3)
>>> set1
{1, 2}
>>> set1.discard(3)
>>> set1
{1, 2}
削除対象が無くてもエラーが発生しない>>> set1={1,2,3}
>>> entity=set1.pop()
>>> set1
{2, 3}
>>> entity
1
どれか一つをとりだす。どれが取り出されるかは不定。取り出すものが無いと KeyError?
>>> set1={1,2,3}
>>> set1.pop()
1
>>> set1.pop()
2
>>> set1.pop()
3
>>> set1.pop()
KeyError: 'pop from an empty set'>>> set1={1,2,3}
>>> set1.clear()
>>> set1
set()>>> set1={1,2,3}
>>> id(set1)
30341040
>>> set2=set1 >>> id(set2) 30341040
>>> id(set1.copy()) 29750136 >>> id(set(set1)) 29750136shallow copy は、元と違うものができる。しかし、shallow copy は一つしか作られないらしい。
>>> import copy >>> id(copy.deepcopy(set1)) 30341160 >>> id(copy.deepcopy(set1)) 29750016deep copy は、毎回違うものが作られる
>>> {1,2,3} == {1,2,3}
True
>>> {1,2,3} != {1,2,3}
False>>> {1,2,3} < {1,2,3}
False
>>> {1,2,3} < {1,2}
False
>>> {1,2,3} < {1,2,3,4}
True>>> {1,2,3} > {1,2,3}
False
>>> {1,2,3} > {1,2}
True
>>> {1,2,3} > {1,2,3,4}
False>>> {1,2,3} <= {1,2,3}
True
>>> {1,2,3} <= {1,2}
False
>>> {1,2,3} <= {1,2,3,4}
True
>>> {1,2,3}.issubset([1,2,3])
True
>>> {1,2,3}.issubset([1,2])
False
>>> {1,2,3}.issubset([1,2,3,4])
True>>> {1,2,3} >= {1,2,3}
True
>>> {1,2,3} >= {1,2}
True
>>> {1,2,3} >= {1,2,3,4}
False
>>> {1,2,3}.issuperset([1,2,3])
True
>>> {1,2,3}.issuperset([1,2])
True
>>> {1,2,3}.issuperset([1,2,3,4])
False>>> {1,2,3} is {1,2,3}
False
>>> set1={1,2,3}
>>> cpy=set1
>>> set1 is cpy
True変更不可のset
>>> set1=set([1,2,3])
>>> set1.add(4)
>>> set1
{1, 2, 3, 4}
>>> set2=frozenset([1,2,3]) >>> set2.add(4) AttributeError: 'frozenset' object has no attribute 'add'
{key:value, key:value, … }
>>> osx = {'siam' : 'beta',
'cheetah' : 10.0,
'puma' : 10.1,
'jaguar' : 10.2,
'panther' : 10.3,
'tiger' : 10.4,
'leopard' : 10.5,
'snow leopard' : 10.6,
'lion' : 10.7,
'mountain lion' : 10.8}
>>> osx
{'tiger': 10.4, 'lion': 10.7, 'puma': 10.1, 'jaguar': 10.2, 'mountain lion': 10.8,
'panther': 10.3, 'cheetah': 10.0, 'siam': 'beta', 'leopard': 10.5, 'snow leopard': 10.6}
dict()
>>> dict(key1='val1', key2='val2')
{'key2': 'val2', 'key1': 'val1'}
>>> dict([('key3','val3'),('key4','val4')])
{'key3': 'val3', 'key4': 'val4'}
>>> dict({'key5':'val5', 'key6':'val6'})
{'key6': 'val6', 'key5': 'val5'}
dict.fromKeys(sequence)
>>> dict.fromkeys(range(6))
{0: None, 1: None, 2: None, 3: None, 4: None, 5: None}
>>> dict.fromkeys(range(6), 'default')
{0: 'default', 1: 'default', 2: 'default', 3: 'default', 4: 'default', 5: 'default'}
Python3 から辞書内包表記が使える
>>> keys=['k1','k2','k3','kk']
>>> vals=['v1','v2','v3','vv']
>>> {key:val for key,val in zip(keys,vals) if key[1:] == val[1:]}
{'k3': 'v3', 'k2': 'v2', 'k1': 'v1'}
>>> osx
{'tiger': 10.4, 'lion': 10.7, 'puma': 10.1, 'jaguar': 10.2, 'mountain lion': 10.8,
'panther': 10.3, 'cheetah': 10.0, 'siam': 'beta', 'leopard': 10.5, 'snow leopard': 10.6}
dict[key]
>>> osx['lion']
10.7
>>> osx.get('siam')
'beta'
dict.get(key) / dict.get(key, default value)
>>> osx.get('tama') is None
True
>>> osx.get('tama', '10.9')
'10.9'
dict.keys()
>>> osx.keys() dict_keys(['tiger', 'lion', 'puma', 'jaguar', 'mountain lion', 'panther', 'cheetah', 'siam', 'leopard', 'snow leopard'])
dict.values()
>>> osx.values() dict_values([10.4, 10.7, 10.1, 10.2, 10.8, 10.3, 10.0, 'beta', 10.5, 10.6])
dict.items()
>>> osx.items()
dict_items([('tiger', 10.4), ('lion', 10.7), ('puma', 10.1), ('jaguar', 10.2),
('mountain lion', 10.8), ('panther', 10.3), ('cheetah', 10.0), ('siam', 'beta'),
('leopard', 10.5), ('snow leopard', 10.6)])
for文では key が取り出せる。順番が不定なことに注意
>>> for key in osx: print(key + "= OSX" + str(osx.get(key))) tiger= OSX10.4 lion= OSX10.7 puma= OSX10.1 jaguar= OSX10.2 mountain lion= OSX10.8 panther= OSX10.3 cheetah= OSX10.0 siam= OSXbeta leopard= OSX10.5 snow leopard= OSX10.6
>>> osx
{'tiger': 10.4, 'lion': 10.7, 'puma': 10.1, 'jaguar': 10.2, 'mountain lion': 10.8,
'panther': 10.3, 'cheetah': 10.0, 'siam': 'beta', 'leopard': 10.5, 'snow leopard': 10.6}
>>> 'leopard' in osx
True
>>> 'tama' in osx
False
>>> osx
{'tiger': 10.4, 'lion': 10.7, 'puma': 10.1, 'jaguar': 10.2, 'mountain lion': 10.8,
'panther': 10.3, 'cheetah': 10.0, 'siam': 'beta', 'leopard': 10.5, 'snow leopard': 10.6}
>>> len(osx)
10
>>> osx
{'tiger': 10.4, 'lion': 10.7, 'puma': 10.1, 'jaguar': 10.2, 'mountain lion': 10.8,
'panther': 10.3, 'cheetah': 10.0, 'siam': 'beta', 'leopard': 10.5, 'snow leopard': 10.6}
>>> osx['siam'] = 'public beta'
>>> osx
{'tiger': 10.4, 'lion': 10.7, 'puma': 10.1, 'jaguar': 10.2, 'mountain lion': 10.8,
'panther': 10.3, 'cheetah': 10.0, 'siam': 'public beta', 'leopard': 10.5, 'snow leopard': 10.6}>>> osx.setdefault('tama', '10.9')
'10.9'
>>> osx
{'leopard': 10.5, 'tiger': 10.4, 'lion': 10.7, 'puma': 10.1, 'jaguar': 10.2, 'panther': 10.3,
'tama': '10.9', 'snow leopard': 10.6, 'cheetah': 10.0, 'siam': 'public beta', 'mountain lion': 10.8}>>> dict1={'k1':'v1','k2':'v2', 'k3':'v3'}
>>> dict2={'k3':'vA','k4':'vB', 'k5':'vC'}
>>> dict1.update(dict2)
>>> dict1
{'k3': 'vA', 'k2': 'v2', 'k1': 'v1', 'k5': 'vC', 'k4': 'vB'}>>> dict1={'k1':'v1','k2':'v2', 'k3':'v3'}
>>> del dict1['k1']
>>> dict1
{'k3': 'v3', 'k2': 'v2'}>>> dict1={'k1':'v1','k2':'v2', 'k3':'v3', 'k4':'v4', 'k5':'v5'}
>>> dict1.pop('k1')
'v1'
>>> dict1
{'k3': 'v3', 'k2': 'v2', 'k5': 'v5', 'k4': 'v4'}
keyが無い場合 KeyError? が発生する。default value を設定すると key が無い場合に dafault value が返却される
>>> dict1.pop('k2')
v2
>>> dict1.pop('k2')
KeyError: 'k2'
>>> dict1.pop('k2','I dont have k2')
'I dont have k2'>>> dict1
{'k3': 'v3', 'k5': 'v5', 'k4': 'v4'}
>>> dict1.popitem()
('k3', 'v3')
>>> dict1.popitem()
('k5', 'v5')
>>> dict1.popitem()
('k4', 'v4')
>>> dict1.popitem()
KeyError: 'popitem(): dictionary is empty'>>> dict1 = {'k1':[1,2,3], 'k2':[4,5,6]}
>>> dict2 = dict1
>>> id(dict1)
140733378109328
>>> id(dict2)
140733378109328>>> dict3 = dict1.copy() >>> id (dict1) 140733378109328 >>> id (dict3) 140733367902720 >>> id (dict1['k1']) 4562201128 >>> id (dict3['k1']) 4562201128
>>> dict4 = dict(dict1) >>> id (dict1) 140733378109328 >>> id (dict4) 140733378119056 >>> id (dict1['k1']) 4562201128 >>> id (dict4['k1']) 4562201128
>>> import copy >>> dict5 = copy.deepcopy(dict1) >>> id (dict1) 140733378109328 >>> id (dict5) 140733378122624 >>> id (dict1['k1']) 4562201128 >>> id (dict5['k1']) 4562201416
>>> dict1 = {'k1':'v1','k2':'v2'}
>>> dict2 = {'k1':'v1','k2':'v2'}
>>> dict1 == dict2
True
>>> dict1 != dict2
False>>> dict3 = {'k3':'v3','k4':'v4'}
>>> dict4 = {'k5':'v5','k6':'v6','k7':'v7'}
>>> dict3 <= dict4
TypeError: unorderable types: dict() <= dict() >>> dict1 = {'k1':'v1','k2':'v2'}
>>> dict2 = {'k1':'v1','k2':'v2'}
>>> dict3 = dict1
>>> dict1 == dict2
>>> dict1 is dict2
False
>>> dict1 is dict3
True>>> dict([('k1','v1'),('k2','v2')])
{'k2': 'v2', 'k1': 'v1'}
>>> from collections import OrderedDict
>>> OrderedDict([('k1','v1'),('k2','v2')])
OrderedDict([('k1', 'v1'), ('k2', 'v2')])
#!/usr/bin/env python
# config : UTF-8
strs=list()
#######################################################################
# '...' も "..." も同じ
strs.append('Single Quotation')
strs.append("Double Quotation")
#######################################################################
# """...""" で囲むと 改行や引用符 がそのまま出力
strs.append("""3 Double Quotation
"123"
"456"
""")
#######################################################################
# エスケープシーケンス
strs.append("abc\n\tdef")
#######################################################################
# r"..." でエスケープシーケンス無効化
strs.append(r"abc\n\tdef")
#######################################################################
# 日本語
strs.append("あいう")
#######################################################################
# メッセージ (Python3 からの書き方)
strs.append("{0} が {1} ました".format("ふとん","ふっとび"))
strs.append("{a} が {b} ました".format(a="アリス",b="走り"))
#######################################################################
# メッセージ (Object)
class City(object):
def __init__(self, name, population):
self.name = name
self.population = population
tokyo = City("東京",1200)
strs.append("{0.name} の人口は {0.population} 万人です".format(tokyo))
#######################################################################
# メッセージ (辞書)
name = {'osaka':'大阪'}
population = {'osaka':886}
strs.append("{0[osaka]} の人口は {1[osaka]} 万人です".format(name, population))
for str in strs:
print(str)
print("--------------------")
$ ./StrExam1.py
Single Quotation
--------------------
Double Quotation
--------------------
3 Double Quotation
"123"
"456"
--------------------
abc
def
--------------------
abc\n\tdef
--------------------
あいう
--------------------
ふとん が ふっとび ました
--------------------
アリス が 走り ました
--------------------
東京 の人口は 1200 万人です
--------------------
大阪 の人口は 886 万人です
--------------------#!/usr/bin/env python
# config : UTF-8
txt = "1234567890壱弐参四五六七八九〇1234567890壱弐参四五六七八九〇"
print(txt)
print("文字数 : " + str(len(txt)))
print("3文字目 =" + txt[2])
print("13文字目 =" + txt[12])
print("前5文字以降 =" + txt[5:])
print("後5文字以全 =" + txt[:-5])
print("前5文字〜後5文字" + txt[5:-5])
print("5〜15文字 =" + txt[5:15])
print("5〜15文字 3文字間隔 =" + txt[5:-5:3])
$ ./StrExam2.py 1234567890壱弐参四五六七八九〇1234567890壱弐参四五六七八九〇 文字数 : 40 3文字目 =3 13文字目 =参 前5文字以降 =67890壱弐参四五六七八九〇1234567890壱弐参四五六七八九〇 後5文字以全 =1234567890壱弐参四五六七八九〇1234567890壱弐参四五 前5文字〜後5文字67890壱弐参四五六七八九〇1234567890壱弐参四五 5〜15文字 =67890壱弐参四五 5〜15文字 3文字間隔 =69弐五八1470参
>>> txt '12345ABCDEF12345ABCDEF'find(), index() は、左から検索。rfind(), rindex() は右から検索
>>> txt.find("345")
2
>>> txt.rfind("345")
13
>>> txt.index("345")
2
>>> txt.rindex("345")
13
find() は、検索文字列が見つからないと -1 を返す
>>> idx = 0
>>> while idx > -1 :
... idx = txt.find("345", idx+1)
... print(idx)
...
2
13
-1
index は ValueError? が発生する
>>> idx = 0
>>> while idx > -1 :
... idx = txt.index("345", idx+1)
... print(idx)
...
2
13
ValueError: substring not found>>> txt '12345ABCDEF12345ABCDEF' >>> len(txt) 22マルチバイト文字であることを意識する必要は無い
>>> len("1234567890壱弐参四五六七八九〇1234567890壱弐参四五六七八九〇")
40'12345ABCDEF12345ABCDEF'
>>> txt.count('345')
2>>> "123".isdigit() True >>> "-123".isdigit() False >>> "百二十三".isdigit() False
>>> "123".isnumeric() True >>> "-123".isnumeric() False >>> "百二十三".isnumeric() True
>>> "123" + "ABC" '123ABC'文字列型以外を連結しようとすると TypeError?
>>> "123" + 456 TypeError: Can't convert 'int' object to str implicitly >>> "123" + str(456) '123456'
>>> ",".join(["123","ABC","!@#"]) '123,ABC,!@#'
>>> '123,ABC,!@#'.split(",")
['123', 'ABC', '!@#']
>>> '123,ABC,!@#'.rsplit(",")
['123', 'ABC', '!@#']
区切り文字を省略すると、スペース区切り (※両端がトリムされる)
>>> ' 123 ABC !@# '.rsplit() ['123', 'ABC', '!@#']
>>> '1st line\n2nd line'.splitlines() ['1st line', '2nd line']第一引数に True を指定すると 改行文字が残される
>>> '1st line\n2nd line'.splitlines(True) ['1st line\n', '2nd line']
>>> '123abc123abc'.partition('b')
('123a', 'b', 'c123abc')
>>> '123abc123abc'.rpartition('b')
('123abc123a', 'b', 'c')>>> '123abc123abc123abc'.replace('abc','xyz')
'123xyz123xyz123xyz'
>>> '123abc123abc123abc'.replace('abc','xyz',2)
'123xyz123xyz123abc'>>> 'TYPE\tRMX11\t$9,250' 'TYPE\tRMX11\t$9,250' >>> 'TYPE\tRMX11\t$9,250'.expandtabs() 'TYPE RMX11 $9,250'
>>> table = str.maketrans('abc','xyz','3')
>>> "abcde12345a1b2c3d4e5".translate(table)
'xyzde1245x1y2zd4e5'
table は dict
>>> type(table)
<class 'dict'>
>>> table
{97: 120, 98: 121, 99: 122, 51: None}
>>> chr(97)
'a'
>>> chr(120)
'x'
辞書は str クラスの static メソッドである str.maketrans() を使う
(Python2 までは string モジュールの一部だったが Python3 から str クラスの static メソッド)
>>> dicTrans={'%FROM%':'manager@acme.co.tk','%TO%':'customer@gmail.com','%SUBJECT%':'Shipping Date'}
>>> table = str.maketrans(dicTrans)
ValueError: string keys in translate table must be of length 1
ぱっと見、誰でもこういう使い方を予想するよねぇ。1文字→1文字の変換辞書を作るので、str.maketrans(辞書) の辞書は要素数が1 でなければならない。>>> "abc".ljust(10) 'abc ' >>> "abc".center(10) ' abc ' >>> "abc".rjust(10) ' abc' >>> "123456".rjust(10,'*') '****123456'
>>> "123456".zfill(10) '0000123456'
>>> 'aaabbbcccbbbaaa'.strip('a')
'bbbcccbbb'
>>> 'aaabbbcccbbbaaa'.rstrip('a')
'aaabbbcccbbb'
>>> 'aaabbbcccbbbaaa'.lstrip('a')
'bbbcccbbbaaa'
>>> ' <tag>value</tag> '.strip()
'<tag>value</tag>'>>> plants = iter(['梅','蘭','菊','竹'])
>>> plants
<list_iterator object at 0x102b7e050>
>>> next(plants)
'梅'
>>> next(plants)
'蘭'
>>> next(plants)
'菊'
>>> next(plants)
'竹'
>>> next(plants)
Traceback (most recent call last):
File "<pyshell#77>", line 1, in <module>
next(plants)
StopIteration
#!/usr/bin/env python
# coding: utf-8
def fibonacci_generator() :
yield 0
yield 1
i = 0
j = 1
while True :
k = i + j
i = j
j = k
yield k
fibonacci = fibonacci_generator()
print([next(fibonacci) for i in range(10)])
$ python fibonnacci.py [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]