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']
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']
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']