2012年3月14日水曜日

開発環境

『初めてのPython 第3版』(Mark Lutz 著、夏目 大 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-393-7)のI部(Pythonの基礎知識)7章(文字列)の問題を解いてみる。

1.

文字列のメソッドfindはリストの検索に使用できない。

2.

スライシングの式はリストに使用できる。

3.

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

4.

Pythonで文字列に直接変更を加えることは出来ないので新しい文字列を作成する必要がある。(元の文字列をスライシング、連結、あるいはreplaceメソッドを使用して利用することはできる。)

5.

値が"s, pa, m"という文字列Sがある場合、中央の2文字を抽出する方法は、スライシング、あるいはsplitメソッドで分割してインデクシングを使う方法がある。

6.

"a\nb\x1f\0000d"は"a", "改行", "b",31(16進数で表記されている), 0(8進数で表記されている)、"d"で6文字。

7.

Python 3.0では使えなくなってしまうから、今後stringモジュールは使うべきではない。

確認。

入出力結果(Terminal)

$ python
Python 2.7.2 (default, Feb 12 2012, 23:50:38) 
[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('a')
2
>>> L=['s','p','a','m']
>>> L.find('a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'find'
>>> L[1:2]
['p']
>>> L[1:4]
['p', 'a', 'm']
>>> 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)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: ord() expected a character, but string of length 4 found
>>> ord('k')
107
>>> chr(107)
'k'
>>> S[2]=z
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'z' is not defined
>>> s=S[0;2]+'abc'
  File "<stdin>", line 1
    s=S[0;2]+'abc'
         ^
SyntaxError: invalid syntax
>>> s=S[0:2]+'abc'
>>> S
'spam'
>>> s
'spabc'
>>> S="s,pa,m"
>>> S[2:4]
'pa'
>>> L=S.split(',')
>>> L
['s', 'pa', 'm']
>>> L[1]
'pa'
>>> S="a\nb\x1f\000d"
>>> S.len()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'len'
>>> len(S)
6
>>> print S
a
bd
>>> quit()
$

0 コメント:

コメントを投稿