Middle letter
Write a function named mid
that takes a string as its parameter. Your function should extract and return the middle letter. If there is no middle letter, your function should return the empty string.
For example, mid("abc")
should return "b"
and mid("aaaa")
should return ""
.
Â
Â
==== SOLUTION ====
“`python
def mid(s):
    length = len(s)
    if length % 2 == 0: # If the length of the string is even
          return “”
    else:
          middle_index = length // 2
          return s[middle_index]
# Test the function
print(mid(“abc”)) # Output: “b”
print(mid(“aaaa”)) # Output: “”
“`
Explanation:
1. `def mid(s):`: This line defines a function named `mid` that takes a string `s` as its parameter.
2. `length = len(s)`: This line calculates the length of the string `s` and stores it in the variable `length`.
3. `if length % 2 == 0:`: This `if` statement checks if the length of the string is even by checking if the length modulo 2 equals 0. If the length is even, it means there is no middle letter, so the function returns an empty string (`””`).
4. `else:`: If the length of the string is odd, execution moves to this `else` block.
5. `middle_index = length // 2`: This line calculates the index of the middle letter by dividing the length of the string by 2 using floor division (`//`), which discards the remainder.
6. `return s[middle_index]`: This line returns the character at the calculated middle index of the string `s`.
So, the function returns the middle letter of the string if the length is odd, and an empty string otherwise.