-2

I'm trying to convert a string to a list of words using python. I want to take something like the following:

string = '"This","is","a","string","with","words!"'

Then convert to something like this :

list = ['This', 'is', 'a', 'string', 'with', 'words']

Notice the omission of punctuation and spaces. What would be the fastest way of going about this?

  • [Use Split per This Post](https://stackoverflow.com/questions/7844118/how-to-convert-comma-delimited-string-to-list-in-python) – DarrylG Nov 10 '19 at 07:05
  • Please always make sure that you post what you have tried along with your question. – Austin Nov 10 '19 at 07:06
  • string = '"This","is","a","string","with","words!"' string.split(',') ['"This"', '"is"', '"a"', '"string"', '"with"', '"words!"'] – Michael Hearn Nov 10 '19 at 07:07

4 Answers4

1

This can quite literally be interpreted as python code using ast.literal_eval. It will produce a tuple but just turn it into a list.

>>> import ast
>>> list(ast.literal_eval(string.replace('!', ''))
['This', 'is', 'a', 'string', 'with', 'words'] 

Or use a list comprehension:

>>> [s.strip('"') for s in string.replace('!','').split(',')]
['This', 'is', 'a', 'string', 'with', 'words'] 
Jab
  • 26,853
  • 21
  • 75
  • 114
0

Assuming the string is always in the format "A","B",..., this should work:

list = list(map(lambda x: x[1:-1], string.split(',')))
Fred Hornsey
  • 309
  • 1
  • 10
  • What about `!` ? – Austin Nov 10 '19 at 07:09
  • Seems like overkill when you could do it with one line using `my_string = '"This","is","a","string","with","words!"'.replace('"','').split(',')` – Reez0 Nov 10 '19 at 07:17
  • Using `map` and `lambda` here is less efficient than just a simple list comprehension just FYI. Either that or use `operator.itemgetter` when using `map` this way – Jab Nov 10 '19 at 07:37
0

Here are some python in-built functions that can help you achieve your desired output:

stringO = '"This","is","a","string","with","words!"'
punctuations = '''!()-[]{};:'"\<>./?@#$%^&*_~'''
string = ""
for char in stringO:
   if char not in punctuations:
       string = string + char

string = string.split(',')
print(string)
Tanish
  • 59
  • 4
0
string = 'This is a string, with words!'
string_to_array = string.split()
print(string_to_array)