مثال 70: بررسی String Object
تا به حال خیلی از stringها استفاده کرده ایم. بیایید بیشتر از ابزاری برای text و به عنوان String Object آنها را بررسی کنیم و propertyها و methodهای آنها را ببینیم. بیایید شروع کنیم:
1- یک string دلخواه تعریف کنید:
my_str = 'hello World!' 2- کلاس آن را بررسی کنید:
type(my_str)
# str 3- حالا docstring این کلاس ( str class ) را ببینید:
print(my_str.__doc__) در خروجی خواهیم داشت:
str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.__str__() (if defined)
or repr(object).
encoding defaults to 'utf-8'.
errors defaults to 'strict'. 4- با متد __dir__ میتوانیم تمام propertyها و methodهای my_str را ببینیم:
my_str.__dir__() در خروجی داریم:
['__new__',
'__repr__',
'__hash__',
'__str__',
'__lt__',
'__le__',
'__eq__',
'__ne__',
'__gt__',
'__ge__',
'__iter__',
'__mod__',
'__rmod__',
'__len__',
'__getitem__',
'__add__',
'__mul__',
'__rmul__',
'__contains__',
'encode',
'replace',
'split',
'rsplit',
'join',
'capitalize',
'casefold',
'title',
'center',
'count',
'expandtabs',
'find',
'partition',
'index',
'ljust',
'lower',
'lstrip',
'rfind',
'rindex',
'rjust',
'rstrip',
'rpartition',
'splitlines',
'strip',
'swapcase',
'translate',
'upper',
'startswith',
'endswith',
'removeprefix',
'removesuffix',
'isascii',
'islower',
'isupper',
'istitle',
'isspace',
'isdecimal',
'isdigit',
'isnumeric',
'isalpha',
'isalnum',
'isidentifier',
'isprintable',
'zfill',
'format',
'format_map',
'__format__',
'maketrans',
'__sizeof__',
'__getnewargs__',
'__doc__',
'__getattribute__',
'__setattr__',
'__delattr__',
'__init__',
'__reduce_ex__',
'__reduce__',
'__getstate__',
'__subclasshook__',
'__init_subclass__',
'__dir__',
'__class__'] 5- بیایید 3 method مربوط به دستکاری text را بررسی کنیم. هرکدام از دستورات زیر را جداگانه اجرا کرده و خروجی را ببینید:
my_str.capitalize() # 'Hello world!'
my_str.upper() # 'HELLO WORLD!'
my_str.replace(' ', '') # 'helloworld!'