Is there a way of simplifying this loop where i replaces whitespace with dashes for each item in a list?
for item in a_list:
alist[alist.index(item)] = '-'.join(item.split(" "))
or is this better?
for item in a_list:
alist[alist.index(item)] = item.replace(" ", "-")
NOTE: The above solution only updates the 1st occurrence in this list, as David suggested, use list comprehension to do the above task.
I have a list of words and some have dashes while some doesn't. The items in a_list looks like this:
this-item has a-dash
this has dashes
this should-have-more dashes
this foo
doesnt bar
foo
bar
The output should look like this, where all items in list should have dashes instead of whitespace:
this-item-has-a-dash
this-has-dashes
this-should-have-more-dashes
this-foo
doesnt-bar
foo
bar
.indexreturns the first index of an item.indexproblems, because at some point that will come up.indexwould work. Once the first of multiple duplicates has been changed once, later duplicates won't try to replace it (or more precisely, if they do try to replace it, it means the duplicate string never had any spaces in it). So this is a rare case whereindexwould work (although it is still not the best solution!!)