问题描述:

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)]

print(first_half)

#the logic behind this is the following

#phrase[:] -> int(/2) -> len(phrase)

#but because int goes before len BUT ends after len

#int(len(phrase)/2)

#__________________________________________________

#breaking down of *first_half* var

#phrase[:int(len(phrase)/2)]

#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 // operator:

>>> s[:len(s)//2]
'My S'
相关阅读:
Top