A PHP Error was encountered

Severity: 8192

Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated

Filename: libraries/Filtered_db.php

Line Number: 23

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

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

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)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now