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

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

Sentry image

Make it make sense

Only the context you need to fix your broken code with Sentry.

Start debugging →