1

For example, I have this list:

['I am the ', 'ugliest person']

I would like to make this list like:

['I-am-the ', 'ugliest-person']
timgeb
  • 76,762
  • 20
  • 123
  • 145
  • 1
    Does this answer your question? [How to replace all occurrences of a string?](https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string) – Red Jun 06 '20 at 18:00
  • @AnnZen It does not. The blank after "the" is not replaced. Also that's a javascript question. – timgeb Jun 06 '20 at 18:03
  • Replace ' ' with - . I think I did something similar earlier today but I'm in my bed & too tired too get up and look. – David Wooley - AST Jun 06 '20 at 18:08
  • What is the issue, exactly? Have you tried anything? – AMC Jun 06 '20 at 18:41

4 Answers4

3

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 ']
Mario Ishac
  • 5,060
  • 3
  • 21
  • 52
2

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]
Yati Raj
  • 456
  • 2
  • 6
  • 10
0

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']
Red
  • 26,798
  • 7
  • 36
  • 58
-1
List = ['test test test ', 'test y jk ']
lenght = len(List)
i = 0
while i < lenght:
   List[i] = List[i].replace(' ', '-')
   i += 1
print(List)
Houda
  • 671
  • 6
  • 16