-4

i do not understand the third line at all, i tried researching in different places i cant seem to find it anywhere. I know what the len function do, but i do not understand the numbers and the division part of this code. What this code does is returning the middle part of each words.

def middle_char(txt):

    return txt[(len(txt)-1)//2:(len(txt)+2)//2]  

print(middle_char("Python"))
print(middle_char("PHP"))
print(middle_char("Java"))
azro
  • 53,056
  • 7
  • 34
  • 70
GS_TEC
  • 1
  • 1

1 Answers1

2

So:

return txt[(len(txt)-1)//2:(len(txt)+2)//2]  

Going from inner to outer:

len(txt)

If txt has a length, len returns that value. For strings, that's the number of characters.

len(txt)-1

Calculate the number of characters in txt and subtract 1 from that value.

(len(txt)-1)//2

// is integer division. The objective here is to ensure the value is not fractional (this is important, since we'll use it as an index for the character sequence in txt).

Given some list l, l[a:b] is a slice that returns all elements between indices a and b (not inclusive of b, so [a, b)).

The outcome this code should produce is to calculate the indices of the midpoint of the string and return that slice (one character for odd-numbered sequences, two for even-numbered).

crcvd
  • 1,465
  • 1
  • 12
  • 23
  • Looks like it returns the single middle character for odd-length strings, the middle two characters for even-length strings. – Fred Larson Mar 16 '21 at 18:22