Course Content
Python Indentation, Comments and Variables
0/2
Object Oriented Programming in Python
0/1
Exception Handling in Python
0/1
Sending emails with Python
0/1
Unit test in python programming
0/1
Python programming (zero to advance!!!)
About Lesson

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.

Join the conversation