i would like to know why int() is used to slice a string in half /2
My current understanding is the following:
phrase = """
It is a really long string
triple-quoted strings are used
to define multi-line strings
first_half = phrase[:int(len(phrase)/2)]
#the logic behind this is the following
#phrase[:] -> int(/2) -> len(phrase)
#but because int goes before len BUT ends after len
#breaking down of *first_half* var
#phrase[:] for a modifier of *phrase* var
#int(/2) to slice *phrase* in half
#and len(phrase) to tell int to slice the length of
#phrase in half with /2 all of this in a variable
#and contained in a single line of code
# BUT, WHY USE int() ?!?!?!?!? Could it be done
# in a different way?
Because if you omit
int, the division (in Python 3) will result in a floating point number when the length is an odd number and slice will raise an error:
>>> s = "My String" >>> s[:len(s)/2] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: slice indices must be integers or None or have an __index__ method
As an alternative, you could use integer division using
>>> s[:len(s)//2] 'My S'