Callum Brown
Callum Brown

Reputation: 147

Python Split string by comma unless proceeded by a space

I have a long string which I need to separate into a list by commas, however when the comma is followed by a space, I do not want it to be separated. e.g:

string:

str = 'foo,bar,hello, you'

desired list:

des_list = ['foo', 'bar', 'hello, you']

Thanks in advance

Upvotes: 1

Views: 126

Answers (2)

soroushamdg
soroushamdg

Reputation: 211

use "split()" function:

str = 'foo,bar,hello, you'
des_list = str.split(',')
#des_list = ['foo', 'bar', 'hello, you']

Upvotes: 0

Andrej Kesely
Andrej Kesely

Reputation: 195418

You can use re module:

import re

txt = 'foo,bar,hello, you'

print( re.split(r',(?=[^\s]+)', txt) )

Prints:

['foo', 'bar', 'hello, you']

Upvotes: 3

Related Questions