Given a string of odd length greater 7, return a string made of the middle three chars of a given String

1. Introduction

In this blog post, we will create a Python program that takes a string of odd length greater than 7 and returns a string made of the middle three characters. This task is an excellent exercise for understanding string slicing and manipulation in Python.

2. Program Steps

1. Ensure the string has an odd length and is greater than 7 characters.

2. Find the index of the middle character of the string.

3. Slice the string to get the middle three characters.

4. Return or print the sliced string.

3. Code Program


def extract_middle_three_chars(input_string):
    # Step 1: Verify the length of the string
    if len(input_string) > 7 and len(input_string) % 2 != 0:
        # Step 2: Find the index of the middle character
        middle_index = len(input_string) // 2

        # Step 3: Slice the string to get the middle three characters
        middle_three = input_string[middle_index - 1 : middle_index + 2]

        # Step 4: Return the sliced string
        return middle_three
    else:
        return "Invalid input"

# Example usage
input_str = "PythonProgramming"
result = extract_middle_three_chars(input_str)
print(f"Middle three characters: {result}")

Output:

For the string 'PythonProgramming', the output will be ram.

Explanation:

1. The function extract_middle_three_chars starts by checking if the input string is of odd length and greater than 7 characters.

2. It calculates the middle_index of the string using len(input_string) // 2. The // operator performs integer division.

3. The middle three characters are extracted using string slicing. The slice input_string[middle_index - 1 : middle_index + 2] starts one character before the middle and ends two characters after, thus capturing the middle three characters.

4. The function returns the middle three characters or "Invalid input" if the input does not meet the criteria.

This method is an effective way to extract specific parts of a string in Python, demonstrating string length verification and slicing techniques.


Comments