ラベル 文字列 の投稿を表示しています。 すべての投稿を表示
ラベル 文字列 の投稿を表示しています。 すべての投稿を表示

2009年10月12日月曜日

文字列

# -*- coding: utf-8 -*-

# 文字列の生成
s = "abc"
s = 'abc'
s = """abc
def"""
s = '''abc
def'''

# 複数行にまたがる場合は \ (バックスラッシュ文字) を使う
# 改行は文字列の中に含まれない
s = "abc\
def"
s = ("abc"
"def")

# 接頭文字 (r, R, u, U, ur, UR, Ur, uR)
s = r"abc\ndef"  # raw文字列 (エスケープシーケンスもそのままの文字になる)
s = R"abc"
s = u"abc"  # Unicode文字列
s = U"abc"
s = ur"abc"  # Unicode & raw
s = UR"abc"
s = Ur"abc"
s = uR"abc"

# 文字列の結合 (文字列リテラルどうしなら + なしでも結合できる)
s = "abc" " def " + s + "abc" + " def"
s = "abc" * 3  # s = "abc" + "abc" + "abc" と同じ

# 文字列フォーマットの操作 (d, i, o, u, x, X, e, E, f, F, g, G, c, r, s, %)
# 結果は "abc, 123, 456.789000"
s = "%s, %d, %f" % ("abc", 123, 456.789)

# 変換フラグ文字 ("#", "0", "-", " ", "+")
# 結果は "'001', '1   ', ' 1,-1', '+1', '456.789'"
s = "'%03d', '%-4d', '% d:% d', '%+d', '%.3f'" %(1, 1, 1,-1, 1, 456.789)

# 指定した位置の文字を取得する
s = s[0]

# スライスする
s = "abcdefg0123456789"[0:10]
# s[i:j:k]: s の i 番目から j 番目まで、k 毎のスライス
s = "abcdefg"[0:7:2]  # "aceg" となる

# 文字列が存在するか調べる
b = "ac" in s
b = "ac" not in s

# 長さを取得する
i = len(s)

# 最大の要素を取得する
s = max("abcdefg")  # "g" が返される 

# 比較する
b = "abc" == "def"
i = cmp("abc", "def")

# 最小の文字を取得する
s = min("abcdefg")  # "a" が返される 

# for文で処理する
for c in s:
    print c

# 文字列型の継承
class A(str):
    pass

文字列メソッド
# 分割してリストで返す
ls = "ab cd ef".split()

# 大文字に変換した文字列を返す
s = "hello".upper()

# 小文字に変換した文字列を返す
s = "HELLO".lower()

# 前後の空白を除去した文字列を返す
s = " hello ".strip()

# 最初の文字を大文字に変換した文字列を返す
s = "hello".capitalize()

# 全てのタブ文字を空白で展開された文字列を返す
s = " hello".expandtabs(4)

# ユニコードに変換する
us = "hello".decode("utf-8")

# エンコードする
s = "hello".encode("shift-jis")

# シーケンスを結合する
s = " ".join(["hello", "world"])  # "hello world" となる

# 文字列が引数で終わっているか調べる
b = "img.jpg".endswith(".jpg")

# 引数で始まっているか調べる
b = "abcde".startswith("abc")

# 英数文字かか調べる
b = "hello123".isalnum()

# 英文字か調べる
b = "hello".isalpha()

# 数字か調べる
b = "123".isdigit()

# 小文字か調べる
b = "hello123".islower()

# 大文字か調べる
b = "HELLO123".isupper()

# 空白文字か調べる
b = "   ".isspace()

# 引数が出現する回数を返
i = "a12b12c12d12e".count("12")

# 引数の出現位置を取得する(存在しないなら -1)
i = "abcdefg".find("e")

# 置き換える
s = "a,b,c,d,e".replace(",", "1")

文字列の連結は
リストに文字列を追加し
文字列メソッドのjoinで文字列に変換する
ls = []

for i in range(100):
    ls.append(str(i))

s = "".join(ls)

詳細はドキュメントで

2009年10月10日土曜日

文字列をzlibで圧縮、展開

# -*- coding: utf-8 -*-

import zlib

s = """このモジュールでは、データ圧縮を必要とするアプリケーションが zlib ライブラリを使って圧縮および解凍を行えるようにします。 zlib ライブラリ自体の Web ホームページは http://www.zlib.netです。 Pythonモジュールと zlib ライブラリの1.1.3より前のバージョンには互換性のない部分があることが知られています。1.1.3にはセキュリティホールが存在しますので、1.1.4以降のバージョンを利用することをお勧めします。

zlib の関数にはたくさんのオプションがあり、しばしば特定の順番で使う必要があります。このドキュメントでは順番のことについて全てを説明し尽くそうとはしていません。信頼できる情報が必要ならば http://www.zlib.net/manual.html にある zlib のマニュアルを参照するようにしてください。 """

c = zlib.compress(s)

dc = zlib.decompress(c)

print len(s)
print len(c)
print len(dc)

実行すると
943
533
943

詳細はドキュメントで

2009年10月6日火曜日

オブジェクトの文字列表現を取得する

# -*- coding: utf-8 -*-

obj = 0.1

print str(obj)
print unicode(obj)
print repr(obj)
print `obj`

# クラスに特殊メソッド __str__ __unicode__ __repr__ を定義すると
# str() unicode() repr() の引数として渡すことが出来る
class A:
    def __str__(self):
        return "abc"
    def __unicode__(self):
        return u"abc"
    def __repr__(self):
        return "def"

a = A()

print str(a)

実行すると
0.1
0.1
0.10000000000000001
0.10000000000000001
abc

reprと``は同じ

詳細はドキュメントで

2009年10月5日月曜日

エスケープシーケンス

\newline     無視
\\           バックスラッシュ (\)
\'           一重引用符 (')
\"           二重引用符 (")
\a           ASCII 端末ベル (BEL)
\b           ASCII バックスペース (BS)
\f           ASCII フォームフィード (FF)
\n           ASCII 行送り (LF)
\N{name}     Unicode データベース中で名前 name を持つ文字 (Unicode のみ)
\r           ASCII 復帰 (CR)
\t           ASCII 水平タブ (TAB)
\uxxxx       16-bit の 16 進数値 xxxx を持つ文字 (Unicode のみ)
\Uxxxxxxxx   32-bit の 16 進数値 xxxxxxxx を持つ文字 (Unicode のみ)
\v           ASCII 水平タブ (VT)
\ooo         8 進数値 ooo を持つ文字
\xhh         16 進数値 hh を持つ文字
詳細はドキュメントで

文字列の長さを取得する

組み込み関数lenを使う

# -*- coding: utf-8 -*-

i = len("hello")

#正確には、文字列の長さではなく
#特殊メソッド__len__が返す値

class A:
    def __len__(self):
        return 34

a = A()
i = len(a)

詳細はドキュメントで

2009年9月29日火曜日

数値を区切りの付いた文字列に変換する

localeモジュールを使う

# -*- coding: utf-8 -*-

import locale

# ロケールを設定する
print locale.setlocale(locale.LC_ALL, "")

# 数値を区切りの付いた文字列に変換する
print locale.format("%d", 123456789, grouping=True)

# 数値を通貨記号の付いた文字列に変換する
print locale.currency(123456789, grouping=True)

# ロケールをen_USに変更する
print locale.setlocale(locale.LC_ALL, ("en_US", "utf-8"))
print locale.format("%d", 123456789, grouping=True)
print locale.currency(123456789, grouping=True)

実行すると
ja_JP.UTF-8
123,456,789
¥123,456,789
en_US.UTF8
123,456,789
$123,456,789.00

Linuxならlocaleコマンドでロケールの情報を取得できる
$ locale -a
C
POSIX
en_AU.utf8
en_BW.utf8
en_CA.utf8
en_DK.utf8
en_GB.utf8
en_HK.utf8
en_IE.utf8
en_IN
en_NG
en_NZ.utf8
en_PH.utf8
en_SG.utf8
en_US.utf8
en_ZA.utf8
en_ZW.utf8
ja_JP.utf8

詳細はドキュメントで

2009年9月28日月曜日

文字列をエンコード

組み込み関数 unicode
文字列メソッド encode decode で変換できる

# -*- coding: utf-8 -*-

u8s = "あ"

# Unicodeに変換する
us = unicode(u8s, "utf-8")
us = u8s.decode("utf-8")

# Unicode文字列をエンコードする
sjs = us.encode("shift-jis")
ejs = us.encode("euc-jp")

def get_code(ch):
    s = "0x"
    for c in ch:
        s += "%x" % ord(c)
    return int(s, 16)

print u8s
print "utf-8: %X" % get_code(u8s)
print "unicode: %X" % get_code(us)
print "shift-jis: %X" % get_code(sjs)
print "euc-jp: %X" % get_code(ejs)

実行すると
あ
utf-8: E38182
unicode: 3042
shift-jis: 82A0
euc-jp: A4A2

詳細はドキュメントで

2009年9月27日日曜日

文字列フォーマットを操作する

s = "%s %d %f" % ("abc", 1, 1.5)
print s

詳細はドキュメントで

文字列を数値に変換する

# -*- coding: utf-8 -*-

# 文字列を数値に変換する
i = int("123")
f = float("1.23")
l = long("123l")
c = complex("123")

# 数値を文字列に変換する
s = str(123)
us = unicode(123)

# クラスに特殊メソッド __int__ __long__ __float__ __complex__ を定義すると
# int() long() float() complex() の引数として渡すことが出来る
class A:
    def __int__(self):
        return 10
    def __long__(self):
        return 100l
    def __float__(self):
        return 1.2
    def __complex__(self):
        return complex(10, 23)

a = A()

print int(a)

詳細はドキュメントで

文字列を実行する

# -*- coding: utf-8 -*-

exec 'print "hello"'

#ファイルの場合は
execfile("filename")

詳細はドキュメントで

文字列を計算する

i = eval("1 + 2")

詳細はドキュメントで

文字コードを文字に変換する

# -*- coding: utf-8 -*-

c = chr(97)

# Unicodeの場合
uc = unichr(97)

# 文字を文字コードに変換する
i = ord('a')

詳細はドキュメントで