0

I have the following string: 'keyword_1, keyword_2, keyword_3'

I want to convert the string into a list with each "keyword" being an element. So it would be: [keyword_1,keyword_2,keyword_3]

How would I go about doing this? Thanks!

1
  • 2
    'keyword_1, keyword_2, keyword_3'.split(", ")? Commented Dec 18, 2014 at 1:18

4 Answers 4

3

Use a list generator with split and trim like:

s = 'keyword_1, keyword_2, keyword_3'
[x.strip() for x in s.split(',')]
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

import re    
re.compile(',\s*').split('keyword_1, keyword_2, keyword_3')

split on , and zero or more space.

4 Comments

That seems to put all 3 keywords into the first element.
try just 'keyword_1, keyword_2, keyword_3'.split(",")
The split method on strings doesn't accept regex arguments.
Hmm...almost. The first element looks right ('keyword_1') but the subsequent elements still contain the space (' keyword_2)
0

try to use siplit

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified, then there is no limit on the number of splits (all possible splits are made). If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, '1,,2'.split(',') returns ['1', '', '2']). The sep argument may consist of multiple characters (for example, '1<>2<>3'.split('<>') returns ['1', '2', '3']). Splitting an empty string with a specified separator returns ['']. If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].

For example, ' 1 2 3 '.split() returns ['1', '2', '3'], and ' 1 2 3 '.split(None, 1) returns ['1', '2 3 '].

&& String to list in Python

Comments

0

If you don't want to import additional modules, you could do something like this:

string = 'keyword_1, keyword_2, keyword_3'
string = string.split(",")
for i in range(len(string)):
    string[i] = string[i].strip()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.