Home > OS >  Idk why the split method works this way
Idk why the split method works this way

Time:03-27

when I type 'a , b, c'.split(',') it would return ['a', ' b', ' c'] why there is a space in ' b' and ' c'?

idk why the answer is ['a', ' b', ' c'] instead of ['a', 'b', 'c'].

CodePudding user response:

Split only splits the string around instances of the delimiter—-it doesn’t also filter out white space, and you’ve asked it to split on the comma not on the space character, so while it looks weird it’s doing what it’s supposed to do. For what it’s worth if you want to split on commas and get rid of leading and trailing white space, you can always apply the trim method to the results (e.g. with list comprehensions or with map).

Disclaimer: if you’re using split to parse CSV data you’re likely better off using the Python CSV package (I don’t remember the name offhand but Google should turn it up quickly), but it’s still good to understand the Python string handling methods.

CodePudding user response:

As an addendum to what has already been said here, you could use re.split to get the behavior you want here:

inp = "a , b, c"
letters = re.split(r'\s*,\s*', inp)
print(letters)  # ['a', 'b', 'c']

CodePudding user response:

You may try something like this

s = 'a , b, c'.replace(' , ',",").replace(', ',',').split(',')
  • Related