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