DEV Community

HHMathewChan
HHMathewChan

Posted on

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

Top comments (0)