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])
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
[…] from yesterday exercise , I search for is there any other way to convert a object from float to integer?The following is my […]