Python Beginner Exercise 2: String

Table of Contents

Question:

  • 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

Solution

My initial solution(Fail)

str1 = "James"  
length_of_name = len(str1)  
print(str1[0]+str1[length_of_name/2]+str1[-1])

Recommend solution

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)

Reflection

  • This time I haven't figure out the correct solution
  • It just keep showing TypeError: string indices must be integers
    • I have also try the string with even number
  • After seeing the recommend solution, I just realise the type of "length_of_name/2" is not default to integers, it doesn't matter the length_of_name is even number or not
    • and confirm by using type() as follow
str1 = "Jamees"  
length_of_name = len(str1)  
half = length_of_name/2  
print(length_of_name)  
print(f"half = {half}")  
print(f"the type of half is {type(half)}")  
#print(str1[0]+str1[half]+str1[-1])
This image is an output of three print statement: first line: the length of the string is 6, second line a variable named half = 3.0 ,third line: the type of half is a float class
This is the output for the above code

So, what to learn is

After the / operator, even the outcome is an integer in maths, its type is a float, must be changed to int for index

exercise from PYnative

One comment

Leave a Reply