Special Functions¶
Python provides several special functions. These special functions are primarily used to convert data types, representing as strings, validating lists etc.
- All operators are typically nothing but functions. We have already seen
operator
which contain the functions. - All the standard classes have special functions called as
__str__
and__repr__
to provide string representation. We will look into the details as part of topics related to object oriented constructs later. - As we explore collections in future, we will observe special functions for operators such as
in
,not in
,len
etc. - We can also use functions (constructors) such as
int
,float
,str
etc to convert the data types.
In [1]:
import operator
In [2]:
operator.add?
Signature: operator.add(a, b, /) Docstring: Same as a + b. Type: builtin_function_or_method
In [3]:
int.__str__?
Signature: int.__str__(self, /) Call signature: int.__str__(*args, **kwargs) Type: wrapper_descriptor String form: <slot wrapper '__str__' of 'object' objects> Namespace: Python builtin Docstring: Return str(self).
In [4]:
int.__repr__?
Signature: int.__repr__(self, /) Call signature: int.__repr__(*args, **kwargs) Type: wrapper_descriptor String form: <slot wrapper '__repr__' of 'int' objects> Namespace: Python builtin Docstring: Return repr(self).
In [5]:
user = '1,123 456 789,Scott,Tiger,1989-08-15,+1 415 891 9002,Forrest City,Texas,75063'
In [6]:
user.split(',')[0]
# Even though user_id is integer, it will be treated as string
# split converts a string to list of strings
Out[6]:
'1'
In [7]:
type(user.split(',')[0])
Out[7]:
str
In [8]:
# We can use int to convert the data type of user_id
user_id = int(user.split(',')[0])
user_id
Out[8]:
1
In [9]:
type(user_id)
Out[9]:
int
In [10]:
l = [1, 2, 3, 4, 2, 1, 8]
In [11]:
l
Out[11]:
[1, 2, 3, 4, 2, 1, 8]
In [12]:
type(l)
Out[12]:
list
In [13]:
2 in l
Out[13]:
True
In [14]:
2 not in l
Out[14]:
False
In [15]:
l.__contains__?
Signature: l.__contains__(key, /) Call signature: l.__contains__(*args, **kwargs) Type: method-wrapper String form: <method-wrapper '__contains__' of list object at 0x7f727ddafe40> Docstring: Return key in self.
In [16]:
l.__contains__(2)
Out[16]:
True