#author("2017-04-05T13:45:38+09:00","","")
-Python関係のWiki
--[[Python]]
--[[Python/MySQL]]
--[[Python/urllib]]
--[[Python/オブジェクト指向]]
--[[Python/外部プログラム実行]]
--[[Python/コマンドライン]]
--[[Python/コンテナ]]
--[[Python/ネットワーク]]
--[[Python/日付・時間]]
--[[Python/ファイル]]
--[[Python/メモリ]]
--[[Python/文字列]]
----

-[[文字列メソッド:http://www.python.jp/doc/2.5/lib/string-methods.html]]
-[[文字列操作の比較表: Ruby, Python, JavaScript, Perl, C++:http://0xcc.net/blog/archives/000137.html]]

* Unicode [#cd742a3b]
-[[PythonのUnicodeEncodeErrorを知る:http://lab.hde.co.jp/2008/08/pythonunicodeencodeerror.html]] ... Pythonで日本語処理するなら読むべし

** 基本 [#hfde4136]
-「unicode型」と、たとえば「UTF-8文字コード列」等の「Unicodeの文字列」は「別物」である
-pythonで国際化されているライブラリやアプリケーション等では、unicode型での入出力を前提にしているものがほとんど
-pythonで日本語を扱う場合においてはunicode型を利用するのが無難
-unicode型のメソッド
--encode( [文字コード] ) ... unicode型を特定の文字コードのバイト列(のstr型)にエンコード
--decode() ... 特定の文字コードのバイト列(のstr型)をデコードしてunicode型に変換
--文字コードを省略したような場合など、「文字コードが指定されていないケースでエンコード」しなければならない局面では、encodeやstrはsys.getdefaultencoding()で取得できる、「デフォルトエンコーディング」の値を使用

** UnicodeEncodeError が出たときの対処法 [#h94bc206]
Pythonで日本語処理していると、こんなエラーによく出くわす
 UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-12: ordinal not in range(128)

こんなエラーが出たら慌てずに以下を行う
-まずは型の確認
 type(ustr)
 <type 'unicode'>

-unicode型 -> str型 
 ustr.encode('utf_8')

- 標準の文字コードの確認
 >>> import sys
 >>> print sys.stdout.encoding
 UTF-8

* 文字コード判別 [#k258b40b]
-[[Python での日本語文字コード判定:http://junaraki.net/blog/2009/04/09/177.html]]

* 文字列処理 関数一覧 [#h916e1ba]
-文字列 → 数値
--int(str)
--float(str)
--long(str)
--complex(str)

-数値 → 文字列
--str(f)

-特定文字除去
--rstrip() ... 行末の空白文字を取り除く。文字を指定しない場合は '\t', '\n', '\r', '\v', '\f' が除去される。

-文字列をリストに分割
--split(ch) ... 指定文字で区切った結果をリストとして取得

-文字列の左寄せ、右寄せ
--ljust(width[, fillchar]) ... width の長さをもつ左寄せした文字列を返す。パディングには fillchar で指定された文字(デフォルトではスペース)が使われる。width が len(s) よりも小さい場合、元の文字列が返される。
--rjust(width[, fillchar]) ... width の長さをもつ右寄せした文字列を返す。パディングには fillchar で指定された文字(デフォルトではスペース)が使われる。width が len(s) よりも小さい場合、元の文字列が返される。

* Tips [#k4113133]
-[[ランダムな文字列生成:http://d.hatena.ne.jp/odz/20070821/1187682903]]

トップ   編集 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS