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 an input string’s first, middle, and last character.
Q:

Write a python program to create a new string made of an input string’s first, middle, and last character.

0

Create a string made of the first, middle and last character

Write a program to create a new string made of an input string’s first, middle, and last character.

Given:

str1 = "James"

Expected Output:

Jms

All Answers

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

Hint:

  • String index always starts with 0
  • Use string indexing to get the character present at the given index
  • Get the index of the middle character by dividing string length by 2

Solution:

  • Use string indexing to get the character present at the given index.
  • Use str1[0] to get the first character of a string and add it to the result variable
  • Next, get the middle character’s index by dividing string length by 2. x = len(str1) /2. Use str1[x] to get the middle character and add it to the result variable
  • Use str1[len(str1)-1] to get the last character of a string and add it to the result variable
  • print result variable to display new string
str1 = 'James'
print("Original String is", str1)

# Get first character
res = str1[0]

# Get string size
l = len(str1)
# Get middle index number
mi = int(l / 2)
# Get middle character and add it to result
res = res + str1[mi]

# Get last character and add it to result
res = res + str1[l - 1]

print("New String:", res)

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