-3

I am trying to join words from a list and convert it to a string

I've tried .join method, but since I only have one item in my list it does not work.

My input = list = ['Vehicles, Parts & Accessories,Automotive Body Paint']

Desired output = str = Vehicles-Parts-&-Accessories-Automotive-Body-Paint

Jonas Palačionis
  • 4,591
  • 4
  • 22
  • 55
  • 4
    I'm not sure that you've provided valid input and output. Please, doublecheck your question and let us know is provided data correct. Also, add what have you tried so far, share your code. – Olvin Roght Sep 10 '19 at 21:00
  • Your example has a single item string in a list, so the task would be to convert the string you have to the one you want. Would a more accurate question be "How to separate words in a string then join by a character?" – fendall Sep 10 '19 at 21:01
  • 1
    Also, what do you want to do with commas? Just ignore them? – quamrana Sep 10 '19 at 21:02
  • If you search in your browser for "Python split string into words" and "Python join words", you'll find references that can explain this much better than we can manage here. – Prune Sep 10 '19 at 21:02
  • Possible duplicate of [How to replace all occurrences of a string?](https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string) – M__ Sep 10 '19 at 21:07
  • Asked and answered many times – M__ Sep 10 '19 at 21:08

3 Answers3

1

First, your list is only one item, so access it by my_str = my_lst[0]. Then remove the , and replace by -:

my_str = my_str.replace(',','').replace(' ', '-')

Output:

'Vehicles-Parts-&-AccessoriesAutomotive-Body-Paint'
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74
0

This does what you're looking for:

lst = ['Vehicles, Parts & Accessories,Automotive Body Paint']
string = lst[0].replace(',',' ').replace(' ','-')

Output:

'Vehicles--Parts-&-Accessories-Automotive-Body-Paint'

Note: try not to use str or list as variable names, because Python reserves those for inner use and you'll disable them that way.

Juan C
  • 5,846
  • 2
  • 17
  • 51
0

You can use regex to do this, let's find all groups of repeated word characters or & and join them with -. Solution works on a list of multiple strings.

import re

l = ['Vehicles, Parts & Accessories,Automotive Body Paint']
['-'.join(re.findall('[\w&]+', words)) for words in l]

Output

['Vehicles-Parts-&-Accessories-Automotive-Body-Paint']
TomNash
  • 3,147
  • 2
  • 21
  • 57