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

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more