Python Beginner Exercise 4: separate a string

Table of Contents

Given:

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

Expected Output:

Displaying each substring

Emma
is
a
data
scientist

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)
  • 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)

Credit

Exercise from Pynative

Leave a Reply