Is there a shortcut to get the middle character of a string?

Question

It is easy to get the last character in a Python string, thanks to the len() function. However, is there a shortcut to get, say, the middle character of a string?

Answer

With some thinking, we can probably realize that if we have the length of a string, we can get the middle character.

Code

# For odd length strings, you can use floor division to get
# the middle index.
# In this string, the middle index is 2.
# len(string1) // 2 = 5 // 2 = 2
string1 = "abcde"

middle = string1[len(string1)//2]
print(middle) # c

# For even length strings, you can offset by 1 to get
# both middle characters.
string2 = "abcdef"

left_middle = string2[(len(string2) - 1) // 2]
right_middle = string2[len(string2) // 2]
print(left_middle, right_middle) # c d
8 Likes

Why there is sign of double division ( // ) instead of single division sign ( / ).

15 Likes

Because he/she doesn’t want a float (=decimal number) as a result but an integer. Then we use “//” instead of “/”.
Otherwise 5/2 would equal 2.5 which can’t be used as an index.

52 Likes

In addition to this, you can find the last element using name_of_list[-1] instead of name_of_list[len(name_of_list)-1]
:slight_smile:
Good coder - lazy coder

3 Likes

Whoah, this is so useful:
instead of using this, I had been casting these values using int() until now.

Thanks a bunch!

2 Likes

It’s because we want an int type, no float or double(decimal) value so we use // Floor Division instead of / Division.

2 Likes