For example, I have this list:
['I am the ', 'ugliest person']
I would like to make this list like:
['I-am-the ', 'ugliest-person']
For example, I have this list:
['I am the ', 'ugliest person']
I would like to make this list like:
['I-am-the ', 'ugliest-person']
You can do this:
lst = ['I am the ', 'ugliest person']
lst = ['-'.join(val.split()) for val in lst]
val.split()
will split val
on any whitespace, and then we rejoin all the split elements with -
.
To preserve any spaces on the edge of each element of lst
, you can add these functions:
def get_ending_spaces(val):
return ' ' * (len(val) - len(val.rstrip()))
def get_beginning_spaces(val):
return ' ' * (len(val) - len(val.lstrip()))
and change the list comprehension to
lst = [get_beginning_spaces(val) + '-'.join(val.split()) + get_ending_spaces(val) for val in lst]
If all your usecases are like your example (where there's no left whitespace), then feel free to remove the get_beginning_spaces
call.
Output for
[' I am the ', ' ugliest person ']
ends up being
[' I-am-the ', ' ugliest-person ']
you can try the below list comprehension
new_list = [x.replace(' ','-') for x in list]
This will create a new list named 'new_list' with the spaces replaced with dashes (-) Hope this helps
Edit: The above code does not preserve the trailing spaces as commented by OP. The below change will probably fix it (only if a single trailing space is involved :/)
new_list = [x[:-1].replace(' ','-') if x[-1]==' ' else x.replace(' ','-') for x in list]
So a proper solution will be more like this:
def replace_spaces(sentence):
l = sentence.split(' ')
l = [x if x for x in l]
return '-'.join(l)
new_list = [ replace_spaces(x) for x in list]
You can use re to do this:
import re
l = ['I am the ', 'ugliest person']
for i,s in enumerate(l):
for n in re.findall('\w *?\w',s): # Finds all spaces that are between 2 letters
s = s.replace(n,n.replace(' ','-')) # Only replace the spaces that are between 2 letters
l[i] = s
print(l)
Output:
['I-am-the ', 'ugliest-person']
List = ['test test test ', 'test y jk ']
lenght = len(List)
i = 0
while i < lenght:
List[i] = List[i].replace(' ', '-')
i += 1
print(List)