Numerical operations have been learned at school, so it doesn't feel strange, but you can also use the +
, *
, and %
operators for character strings.
I still understand +
and *
, but I was surprised that %
can be used as a format converter.
>>> 'ABC' + '123'
'ABC123'
>>> 'ABC' * 3
'ABCABCABC'
>>> '%#08x' % 123
'0x00007b'
>>> '%d, %x, %o' % (123, 123, 123)
'123, 7b, 173'
Python is an object-oriented scripting language, and strings will have processing methods, so let's take a look at the method list of strings.
>>> dir('') # ''The part of can be any character string
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', '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']
The latter half from capitalize is a normal method for strings.
>>> help(''.capitalize)
Help on built-in function capitalize:
capitalize(...)
S.capitalize() -> string
Return a copy of the string S with only its first character
capitalized.
>>> 'ABC'.capitalize()
'Abc'
>>> help(''.center)
Help on built-in function center:
center(...)
S.center(width[, fillchar]) -> string
Return S centered in a string of length width. Padding is
done using the specified fill character (default is a space)
>>> 'Python'.center(30, '-')
'------------Python------------'
The first half of the __
(two underscores) displayed by dir ('')
is the special method
, which seems to be used in a fixed way.
__add__
, __mul__
, __mod__
are the methods called by the+
,*
,%
operators.
>>> 'ABC'.__add__('123')
'ABC123'
>>> 'ABC'.__mul__(3)
'ABCABCABC'
>>> '%#x'.__mod__(123)
'0x7b'
Thanks to the string class defining these methods, you can manipulate strings using operators.
So what about this?
>>> 'ABC' + '123' * 3
'ABC123123123'
>>> 'ABC'.__add__('123').__mul__(3)
'ABC123ABC123ABC123'
The result is different between the above formula and the bottom formula.
Operators have precedence, and *
takes precedence over+
, so the Python interpreter interprets the above expression as'ABC' + ('123' * 3)
and: The result is different because the method is called to.
>>> 'ABC'.__add__('123'.__mul__(3))
'ABC123123123'
By the way, let's call the method for numerical values as well.
>>> dir(0) #0 can be another number
['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']
>>> 123.__add__(456)
SyntaxError: invalid syntax
>>> 123 .__add__(456)
579
>>> (123).__add__(456)
579
This is because 123.__ add__ (456)
is a syntax error, but .
is interpreted as a decimal point. You can call the method by leaving a space or enclosing it in parentheses.
By the way, the built-in function len function calls the __len__
method.
Personally, I'd like to define another name for the length ()
method as well.
>>> len('abcdefg')
7
>>> 'abcdefg'.__len__()
7
There are other special methods used for comparison operators, array access, sequential access, reduce (), etc.
Recommended Posts