Home > Python Archive
Python Archive
Python: リスト中の文字列を大文字⇔小文字に変換
- 2008-08-03 (日)
- Python
文字列を比較する際に、大文字・小文字を区別したくない場合があります。その時は、比較する文字列を大/小文字列のどちらかに統一しておく、という手があります。Pythonでは大文字・小文字変換メソッドlower()、upper()はstringオブジェクトに組み込まれています。
今回は、その使い方と実際に使用する状況に近いデータ構造、ここでは変換対象文字列がリスト中の要素である場合を想定し、for文とリストコンプリヘンション(リスト内包表記)の両表記を以下に示します。
ソースコード
#!/usr/bin/python
# coding: UTF-8
# リスト中の文字列要素を大文字⇔小文字変換
str_atog = "ABCDEFG"
str_hton = "hijklmn"
# lower(), upper()メソッドの使い方
print "大文字(列) %s を小文字(列) %s に変換" % (str_atog, str_atog.lower())
print "小文字(列) %s を大文字(列) %s に変換" % (str_hton, str_hton.upper())
print
arr = ['And', 'Begin', 'Code', 'Double']
arr2 = ['end', 'flag', 'gem', 'halt']
# for文で小文字[大文字](列)を要素とするリストを生成
n_arr = []
for str in arr:
n_arr.append(str.lower())
print n_arr
n_arr2 = []
for str in arr2:
n_arr2.append(str.upper())
print n_arr2, 'n'
# リストコンプリヘンションで小文字[大文字](列)を要素とするリストを生成
print [str.lower() for str in arr]
print [str.upper() for str in arr2]
実行結果
大文字(列) ABCDEFG を小文字(列) abcdefg に変換 小文字(列) hijklmn を大文字(列) HIJKLMN に変換 ['and', 'begin', 'code', 'double'] ['END', 'FLAG', 'GEM', 'HALT'] ['and', 'begin', 'code', 'double'] ['END', 'FLAG', 'GEM', 'HALT']
List Comprehensions ならワンライナーで書けるってのは地味に良いですね。
話変わりますが、Rubyにもイテレータやブロックを用いた簡略記法がありましたね。アレはアレで、応用しやすいものです。
チュートリアル
リファレンス
- Comments: 0
- Trackbacks: 0
Python: if/for文でのin演算子の各オブジェクト毎の評価
- 2008-08-02 (土)
- Python
if/for文中で使われるin演算子の評価はオブジェクトごとに微妙に変化します。あやふやなままにしておくのもなんですし、ここで、以下のオブジェクトに対するif/for文中の評価を実際に確認してみましょう。
- 文字列
- リスト
- 数値のリスト
- 文字列のリスト
- 辞書のリスト
- 辞書
if/for文 + in 文字列
#!/usr/bin/python
# coding: UTF-8
str1 = "abcdefghijklmn" # 文字列
# if 「検索する文字列」 in 「検索される文字列」:
elem = 'def'
if elem in str1:
print '文字列 "%s" に "%s" は存在する。' % (str1, elem)
print
# for 「要素(文字)」 in 「文字列」:
for ch in str1:
print ch, # str1の先頭の文字から順に繰り返す
実行結果
文字列 "abcdefghijklmn" に "def" は存在する。 a b c d e f g h i j k l m n
if/for文 + in リスト
#!/usr/bin/python
# coding: UTF-8
nums = [1, 2, 3, 4, 5] # 数値のリスト
chs = ['a', 'b', 'c', 'd'] # 文字列のリスト
dics = [{'one':1}, {'two':2}, {'three':3}, {'four':4}] # 辞書のリスト
# if 「検索する要素」 in 「検索されるリスト」:
elem = 3
if elem in nums:
print 'リスト %s に要素の %d は存在する。' % (nums, elem)
elem = 'b'
if elem in chs:
print 'リスト2 %s に要素の %s は存在する。' % (chs, elem)
elem = {'two':2}
if elem in dics:
print 'リスト3 %s に要素の %s は存在する。' % (dics, elem)
print
# for 「リストの要素」 in 「リスト」:
for e_num in nums:
print e_num,
print
for e_ch in chs:
print e_ch,
print
for e_dic in dics:
print e_dic,
実行結果
リスト [1, 2, 3, 4, 5] に要素の 3 は存在する。
リスト2 ['a', 'b', 'c', 'd'] に要素の b は存在する。
リスト3 [{'one': 1}, {'two': 2}, {'three': 3}, {'four': 4}] に要素の {'two': 2} は存在する。
1 2 3 4 5
a b c d
{'one': 1} {'two': 2} {'three': 3} {'four': 4}
if/for文 + in 辞書
#!/usr/bin/python
# coding: UTF-8
dic = {'one':1, 'two':2, 'three':3, 'four':4} # 辞書
# if 「検索するキー」 in 「検索される辞書」:
elem = 'three'
if elem in dic: # 辞書のキーの検索
print '辞書 %s に要素の「キー」 %s は存在する。' % (dics, elem)
print
# for 「辞書のキー」 in 「辞書」:
for key in dic: # for key in dic.keys(): と同じ
print key,
print
for v in dic.values(): # 値を要素として繰り返す
print v,
print
for (k, v) in dic.items(): # (キー, 値)のタプルを要素として繰り返す
print "%s:%s, " % (k, v),
実行結果
辞書 [{'one': 1}, {'two': 2}, {'three': 3}, {'four': 4}] に要素の「キー」 three は存在する。
four three two one
4 3 2 1
four:4, three:3, two:2, one:1,
チュートリアル
リファレンス
- Comments: 0
- Trackbacks: 0
Python: コマンドライン引数の取得 - sys.argv変数
- 2008-07-26 (土)
- Python
コマンドラインで与える引数によってプログラムの挙動を変えたいという場面はよくあります。Python ではコマンドライン引数は sys モジュールの argv 属性に文字列を要素とするリストとして格納されています。そして、リストの先頭要素(sys.argv[0])はスクリプトファイル名となっています。
ソースコード
# coding: Shift_JIS
import sys # モジュール属性 argv を取得するため
argvs = sys.argv # コマンドライン引数を格納したリストの取得
argc = len(argvs) # 引数の個数
# デバッグプリント
print argvs
print argc
print
if (argc != 2): # 引数が足りない場合は、その旨を表示
print 'Usage: # python %s filename' % argvs[0]
quit() # プログラムの終了
print 'The content of %s ...n' % argvs[1]
f = open(argvs[1])
line = f.readline() # 1行読み込む(改行文字も含まれる)
while line:
print line
line = f.readline()
f.close
text.txt
It is meaningless only to think my long further aims idly. It is important to set my aims but at the same time I should confirm my present condition. Unless I set the standard where I am in any level, I'll be puzzled about what I should do from now on.
実行結果
引数を指定しない場合
$ python argv01.py ['argv01.py'] 1 Usage: # python SCRIPTNAME.py filename
引数を指定した場合
$ python argv01.py text.txt ['argv01.py', 'text.txt'] 2 The content of text.txt ... It is meaningless only to think my long further aims idly. It is important to set my aims but at the same time I should confirm my present condition. Unless I set the standard where I am in any level, I'll be puzzled about what I should do from now on.
リファレンス
- Comments: 0
- Trackbacks: 1
Python: 正規表現の基本 - 文字範囲の指定「[ ]」
- 2008-07-21 (月)
- Python
ソースコード
# coding: Shift_JIS
import re # 正規表現を扱うモジュールのインポート
# 正規表現のチェックプリント用の関数
def PrintRegMatch(pat, txt):
# 探索される文字列をテキスト
# 探索する 文字列をパターン
# 書式: re.match(パターン, テキスト)
m = re.match(pat, txt) # パターンにマッチしなかった場合はNoneを返す
if m != None: print 'パターン"%s"はテキスト"%s"にマッチ「する」' % (pat, txt)
else: print 'パターン"%s"はテキスト"%s"にマッチ「しない」' % (pat, txt)
# []で括られた文字の内どれか1つにマッチすれば真
PrintRegMatch('[ABC]D', 'CD') # A or B or C の次に D がくるパターンにマッチ
PrintRegMatch('[A-C]E', 'CE') # [A-C]は[ABC]と同意
print
# [A-Z]は全てのアルファベット大文字の内のどれか1つの意
PrintRegMatch('[A-Z]*END', 'CHSHSBSRAWRGARENDGREW')
PrintRegMatch('A[A-Z]*E', 'AgafgafE')
PrintRegMatch('A[a-z]*E', 'AewnglfngowE')
# [0-9]は0~9の数字の内どれか1つの意
PrintRegMatch('[0-9]*-[0-9]*-[0-9]*', '03-3333-2222')
print
# []内の「^」否定
PrintRegMatch('[^ABC]D', 'DD') # A or B or C でない文字の次に D がくるパターンにマッチ
PrintRegMatch('[^A-Z]*-[^A-Z]*', '164-9999')
print
PrintRegMatch('[ABC][DEF]', 'CE')
PrintRegMatch('[ABC][DEF]', 'CC')
PrintRegMatch('[a-zA-Z]*', 'FjAVzxRUqyOIn')
PrintRegMatch('[a-z][A-Z]*', 'FjAVzxRUqyOIn')
PrintRegMatch('[a-z]*[A-Z]*', 'FjAVzxRUqyOIn')
実行結果
パターン"[ABC]D"はテキスト"CD"にマッチ「する」 パターン"[A-C]E"はテキスト"CE"にマッチ「する」 パターン"[A-Z]*END"はテキスト"CHSHSBSRAWRGARENDGREW"にマッチ「する」 パターン"A[A-Z]*E"はテキスト"AgafgafE"にマッチ「しない」 パターン"A[a-z]*E"はテキスト"AewnglfngowE"にマッチ「する」 パターン"[0-9]*-[0-9]*-[0-9]*"はテキスト"03-3333-2222"にマッチ「する」 パターン"[^ABC]D"はテキスト"DD"にマッチ「する」 パターン"[^A-Z]*-[^A-Z]*"はテキスト"164-9999"にマッチ「する」 パターン"[ABC][DEF]"はテキスト"CE"にマッチ「する」 パターン"[ABC][DEF]"はテキスト"CC"にマッチ「しない」 パターン"[a-zA-Z]*"はテキスト"FjAVzxRUqyOIn"にマッチ「する」 パターン"[a-z][A-Z]*"はテキスト"FjAVzxRUqyOIn"にマッチ「しない」 パターン"[a-z]*[A-Z]*"はテキスト"FjAVzxRUqyOIn"にマッチ「する」
リファレンス
- Comments: 0
- Trackbacks: 0
Python: 正規表現の基本 - 繰り返し「*」「+」「?」
- 2008-07-20 (日)
- Python
ソースコード
# coding: Shift_JIS
import re # 正規表現を扱うモジュールのインポート
# 正規表現のチェックプリント用の関数
def PrintRegMatch(pat, txt):
# 書式: re.match(パターン, テキスト)
m = re.match(pat, txt) # パターンにマッチしなかった場合はNoneを返す
if m != None: print 'パターン"%s"はテキスト"%s"にマッチ「する」' % (pat, txt)
else: print 'パターン"%s"はテキスト"%s"にマッチ「しない」' % (pat, txt)
txt = 'ABCDEFGH' # 探索される文字列をテキスト
# 探索する 文字列をパターン
# 「*」: 直前の文字の0回以上の繰り返しにマッチ
PrintRegMatch('.*CDE', txt)
PrintRegMatch('A.*H', txt)
PrintRegMatch('A*BC', txt)
PrintRegMatch('A.*BC', txt)
PrintRegMatch('A*', '')
print
# 「+」: 直前の文字の1回以上の繰り返しにマッチ
PrintRegMatch('.+DEF', txt)
PrintRegMatch('A.+H', txt)
PrintRegMatch('A+BC', txt)
PrintRegMatch('A.+BC', txt)
PrintRegMatch('A+', '')
print
# 「?」: 直前の文字の0or1回の繰り返しにマッチ
PrintRegMatch('^A?.+$', txt)
PrintRegMatch('^B?$', '')
PrintRegMatch('^C?E', 'E')
PrintRegMatch('A.?H', txt)
PrintRegMatch('BBB?C', 'BBC')
実行結果
パターン".*CDE"はテキスト"ABCDEFGH"にマッチ「する」 パターン"A.*H"はテキスト"ABCDEFGH"にマッチ「する」 パターン"A*BC"はテキスト"ABCDEFGH"にマッチ「する」 パターン"A.*BC"はテキスト"ABCDEFGH"にマッチ「する」 パターン"A*"はテキスト""にマッチ「する」 パターン".+DEF"はテキスト"ABCDEFGH"にマッチ「する」 パターン"A.+H"はテキスト"ABCDEFGH"にマッチ「する」 パターン"A+BC"はテキスト"ABCDEFGH"にマッチ「する」 パターン"A.+BC"はテキスト"ABCDEFGH"にマッチ「しない」 パターン"A+"はテキスト""にマッチ「しない」 パターン"^A?.+$"はテキスト"ABCDEFGH"にマッチ「する」 パターン"^B?$"はテキスト""にマッチ「する」 パターン"^C?E"はテキスト"E"にマッチ「する」 パターン"A.?H"はテキスト"ABCDEFGH"にマッチ「しない」 パターン"BBB?C"はテキスト"BBC"にマッチ「する」
リファレンス
- Comments: 0
- Trackbacks: 0
Home > Python Archive