How to find the middle character of a string in python

Last update on August 19 2022 21:50:48 [UTC/GMT +8 hours]

Python Basic - 1: Exercise-93 with Solution

Write a Python program to find the middle character[s] of a given string. If the length of the string is even return the two middle characters. If the length of the string is odd, return the middle character.

Sample Solution:

Python Code:

def middle_char[txt]:
  return txt[[len[txt]-1]//2:[len[txt]+2]//2]
text = "Python"
print["Original string: ",text]
print["Middle character[s] of the said string: ",middle_char[text]]
text = "PHP"
print["Original string: ",text]
print["Middle character[s] of the said string: ",middle_char[text]]
text = "Java"
print["Original string: ",text]
print["Middle character[s] of the said string: ",middle_char[text]]

Sample Output:

Original string:  Python
Middle character[s] of the said string:  th
Original string:  PHP
Middle character[s] of the said string:  H
Original string:  Java
Middle character[s] of the said string:  av

Pictorial Presentation:


Flowchart:

Python Code Editor:

Have another way to solve this solution? Contribute your code [and comments] through Disqus.

Previous: Write a Python program to compute cumulative sum of numbers of a given list.
Next: Write a Python program to find the largest product of the pair of adjacent elements from a given list of integers.

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Given string str, the task is to print the middle character of a string. If the length of the string is even, then there would be two middle characters, we need to print the second middle character.

    Examples:

    Input: str = “Java”
    Output: v
    Explanation: 
    The length of the given string is even. 
    Therefore, there would be two middle characters ‘a’ and ‘v’, we print the second middle character.

    Input: str = “GeeksForGeeks”
    Output: o
    Explanation: 
    The length of the given string is odd. 
    Therefore, there would be only one middle character, we print that middle character.

    Approach:

    1. Get the string whose middle character is to be found.
    2. Calculate the length of the given string.
    3. Finding the middle index of the string.
    4. Now, print the middle character of the string at index middle using function charAt[] in Java.

    Below is the implementation of the above approach:

    C++

    #include

    using namespace std;

    void  printMiddleCharacter[string str]

    {

        int len = str.size[];

        int middle = len / 2;

        cout

    Chủ Đề