Q:

Write a python program to create a new string made of the middle three characters of an input string.

belongs to collection: Python String Exercises

2

Create a string made of the middle three characters

Write a program to create a new string made of the middle three characters of an input string.

Given:

Case 1

str1 = "JhonDipPeta"

Output

Dip

Case 2

str2 = "JaSonAy"

Output

Son

 

 

 

 

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Hint:

  • First, get the middle index number by dividing string length by 2.
  • Use string slicing to get the middle three characters starting from the middle index to the next two character

Solution:

  • Get the middle character’s index using x = len(str1) /2.
  • Use string slicing to get the middle three characters starting from the middle index to the next two character str1[middle_index-1:middle_index+2]
def get_middle_three_chars(str1):
    print("Original String is", str1)

    # first get middle index number
    mi = int(len(str1) / 2)

    # use string slicing to get result characters
    res = str1[mi - 1:mi + 2]
    print("Middle three chars are:", res)

get_middle_three_chars("JhonDipPeta")
get_middle_three_chars("JaSonAy")

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python String Exercises

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Append new string in the middle of a given string ... >>
<< Write a python program to create a new string made...