2012年5月20日日曜日

開発環境

『初めてのPython 第3版』(Mark Lutz 著、夏目 大 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-393-7) のII部(ビルトインオブジェクト)の7章(文字列)の練習問題を解いてみる。

1.

文字列のメソッドは文字列のみに使うことが出来て、リストの検索には使用できない。

2.

スライシングはシーケンスに使えるので、文字列でもリストでも使える。

3.

文字列をASCIIのコード(整数)に変換するにはord関数、反対に整数を文字に変換するにはchr関数を使えばいい。

4.

Pythonで文字列を変更を加えるには、新しい文字列を作成する。(文字列は不変性を持つので直接は変更できない。

5.

中央の2文字を抽出する方法はスライシングを行うか、splitで分割してインデクシングかの2つの方法がある。

6.

a, \n, b, \x1f, \00, dの6文字。

7.

python3ではstringモジュールは廃止されるのでstringモジュールは使用するべきではない。

対話型コマンドラインで確認。

入出力結果(Terminal)

$ python
Python 3.2.3 (default, Apr 18 2012, 20:17:30) 
[GCC 4.2.1 Compatible Apple Clang 3.0 (tags/Apple/clang-211.12)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> s="spam"
>>> s.find('p')
1
>>> l=['s','p','a','m']
>>> l.find('p')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'find'
>>> s[1:3]
'pa'
>>> l[1:3]
['p', 'a']
>>> ord(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: ord() expected a character, but string of length 4 found
>>> ord('s')
115
>>> chr(115)
's'
>>> s+='python'
>>> s
'spampython'
>>> s=s[0:]
>>> s
'spampython'
>>> s=[:5]
  File "<stdin>", line 1
    s=[:5]
       ^
SyntaxError: invalid syntax
>>> s=s[:5]
>>> s
'spamp'
>>> s=s[:4]
>>> s
'spam'
>>> s.replace('s','sssss')
'ssssspam'
>>> s
'spam'
>>> s=s.replace('s','aaaa')
>>> s
'aaaapam'
>>> s="s,pa,m"
>>> s[2:4]
'pa'
>>> s.splie(,)[1]
  File "<stdin>", line 1
    s.splie(,)[1]
            ^
SyntaxError: invalid syntax
>>> s.split(',')[1]
'pa'
>>> len("a\nb\x1f\000d")
6
>>> quit()
$

0 コメント:

コメントを投稿