DEV Community

HHMathewChan
HHMathewChan

Posted on

3 2

Python daily exercise 4: separate a string

Question

  • Write a program to split a given string on hyphens and display each substring.

Given:

str1 = "Emma-is-a-data-scientist"
Enter fullscreen mode Exit fullscreen mode

Expected Output:

Displaying each substring

Emma
is
a
data
scientist
Enter fullscreen mode Exit fullscreen mode

My attempt

  • don't know what to do, look at the hint and it ask me to use split method
  • After looking up the split syntax, my first try

Fail

str1 = "Emma-is-a-data-scientist"  

new_str = str1.split()
print("Displaying each substring") 
for word in new_str:  
    print(word)
Enter fullscreen mode Exit fullscreen mode
  • First, I thought that the split method will return a list, i can just iterate over it. However the output is still the original list Emma-is-a-data-scientist.
  • Then I look to the syntax carefully, the split method is default to separate by whitespace and now there is no white space, so the separator needs to be "-".

Success

str1 = "Emma-is-a-data-scientist"  

new_str = str1.split("-")  
print("Displaying each substring")  
for word in new_str:  
    print(word)
Enter fullscreen mode Exit fullscreen mode

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 (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more