0

If i have a string of words separated by colons or hyphens what would be the best method of putting them into a list?

string = ('car:boat:motorcycle:plane') 

into

list = ['car', 'boat', 'motorcycle', 'plane']
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
nosey
  • 1
  • 1

1 Answers1

1

Use the split method and pass the separator

string.split(":")

Default separator is any whitespace.

An optional second argument, maxsplit, will tell Python to split only that number of times:

string.split(":", 2) results in ['car', 'boat', 'motorcycle:plane']

Heitor Chang
  • 6,038
  • 2
  • 45
  • 65