Replace spaces with dashes for each element in a -python list

advertisements

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


Use a list comprehension:

a_list = [e.replace(" ", "-") for e in a_list]