0

Assuming the string has at least one character in it. If the string length is odd, then you may assume it returns (−1)/2 characters where n represents how many characters are in the original string.

For example:

'small' => 'sm'

I would also like to write another function that returns the 2nd half of a string.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
scout112
  • 49
  • 5
  • 1
    Have you tried anything at all that we can help with? – Tomerikoo Oct 06 '20 at 10:36
  • 1
    Does this answer your question? [Understanding slice notation](https://stackoverflow.com/questions/509211/understanding-slice-notation). Together with [`len()`](https://docs.python.org/3/library/functions.html#len) this will help you get the solution. – Tomerikoo Oct 06 '20 at 10:36
  • A few more relevant questions from this site: https://stackoverflow.com/questions/4789601/split-a-string-into-2-in-python ; https://stackoverflow.com/questions/39311341/divide-a-string-into-two-halves-in-python ; https://stackoverflow.com/questions/62160102/splitting-strings-in-half-python ; https://stackoverflow.com/questions/48934246/split-python-string-into-two-on-newline-nearest-the-middle – Tomerikoo Oct 06 '20 at 10:43

1 Answers1

0

You can just do an integer division (//) to get the integer value of the division to get the desired (n-1)/2 value for odd n. Therefore, having the following:

>>> my_string = "small"
>>> print(my_string[:len(my_string)//2])
sm

You could do the similar thing with using math.floor to be more explicit, but result is the same.