プロが教えるわが家の防犯対策術!

初心者のくせに、Pythonでプログラムを学びだしました。
すっごく初歩的な質問なんですが、
Pythonには
int()という文字列を数字に変換する関数があるのですが、
a="4232"を数字に
変換するとき、
int(a)とやるみたいですが、
a.int()ではダメなんですか?
違いがわかりません。
また、一部だけ指定してやるとき、
a.int("32")とやればいいのですか?

このへんで混乱しているので、
わかりやすくご教授してください。

A 回答 (1件)

>int(a)とやるみたいですが、


>a.int()ではダメなんですか?
やってみましたか?

>>> x = "123"
>>> x
'123'
>>> type(x)
<type 'str'>
>>> x.int()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'int'
>>> dir(x)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__ge__', '__getattribute__', '__getitem__',
'__getnewargs__', '__getslice__', '__gt__', '__hash__',
'__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__',
'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__rmod__', '__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode',
'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum',
'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper',
'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace',
'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit',
'rstrip', 'split', 'splitlines', 'startswith', 'strip',
'swapcase', 'title', 'translate', 'upper', 'zfill']
>>>

Pythonの場合、文字列オブジェクトにはint()というメソッドはありませんから
エラーになると言うわけです。
前者は関数を呼び出しますが、後者は . の前のオブジェクトのメソッドを呼び出します。
    • good
    • 0
この回答へのお礼

ありがとうございました

お礼日時:2009/06/01 20:24

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!