DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

HHMathewChan
HHMathewChan

Posted on • Updated on

Python daily exercise 2: string

Question:

  • Write a program to create a new string made of an input string’s first, middle, and last character.
  • Given
str1 = "James"
Enter fullscreen mode Exit fullscreen mode
  • expected output
Jms
Enter fullscreen mode Exit fullscreen mode

Solution

My initial solution(Fail)

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

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)

Enter fullscreen mode Exit fullscreen mode

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])
Enter fullscreen mode Exit fullscreen mode

The length of a string is 6, the half of the length is 3.0, it is a float type

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

Top comments (2)

Collapse
jmagave profile image
jmagave

Using integer division operator // instead of /

s = "James"
print(s[0]+s[len(s) // 2]+s[-1:] if  len(s) > 2 else "Too small") 
Enter fullscreen mode Exit fullscreen mode

Caveat emptor, do not handle

Collapse
mathewchan profile image
HHMathewChan Author

your solution looks much better, good to learn from this

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.