Knowee
Questions
Features
Study Tools

Write a functionstring middle(string str)that returns a string containing the middle character in str if the length of str is odd,or the two middle characters if the length is even. For example, middle("middle")returns "dd" .

Question

Write a functionstring middle(string str)that returns a string containing the middle character in str if the length of str is odd,or the two middle characters if the length is even. For example, middle("middle")returns "dd" .

🧐 Not the exact question you are looking for?Go ask a question

Solution

Sure, here is a Python function that does what you asked for:

def middle(str):
    length = len(str)
    if length % 2 == 0:
        return str[length // 2 - 1:length // 2 + 1]
    else:
        return str[length // 2]

This function works by first determining the length of the input string. If the length is even, it returns the two middle characters by slicing the string at the appropriate indices. If the length is odd, it returns the single middle character.

This problem has been solved

Similar Questions

Write a Python function to insert a string in the middle of a string.

#include <iostream> #include <string> using namespace std; string middle(string str) { int length = str.length(); if(length % 2 == 0) { return str.substr(length / 2 -1, 2); } else { return str.substr(length/2, 2); } } int main() { string word, result; cout << "Enter the word: "; cin >> word; result = middle(word); cout << result << "\n"; return 0; }

Write a function x_at_either_end(string) that takes a string string as a parameter, which may be empty, and returns a boolean. It returns True if and only if the string string starts or ends with the lower-case character x.We recommend using the startswith and endswith methods of str.

Which method can be used to return a string in upper case letters?

Implement a function to swap the odd and even-indexed characters in a given string.swap_odd_even_chars(String text): that takes a string as input and returns the odd and even-indexed characters swapped string as output.Example - 1 : Input:String text = “abcdefgh”swap_odd_even_chars(text) Output:  'badcfehg'

1/1

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.