DEV Community

HHMathewChan
HHMathewChan

Posted on • Edited on

5 2

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

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

your solution looks much better, good to learn from this

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs