3

Possible Duplicate:
Split string into a list in Python

I have a string with a lot of part-strings

>>> s = 'str1, str2, str3, str4'

now I have a function like following

>>> def f(*args):
        print(args)

what I need, is to split my string into multiple strings, so that my function prints something like this

>>> f(s)
('str1', 'str2', 'str3', 'str4')

Has someone an idea, how I can perform this?

  • edit: I did not searched a function to split a string into an array of Strings.

This is what i searched for.

>>> s = s.split(', ')
>>> f(*s)
('str1', 'str2', 'str3', 'str4')
Community
  • 1
  • 1
knumskull
  • 186
  • 1
  • 2
  • 8
  • 6
    I'm puzzled by questions like this. Everyone has plenty of basic doubts when starting with a new language, but did you try searching for 'python split string' in your search engine of choice or this site's search feature? – Eduardo Ivanec Mar 14 '12 at 14:13
  • @Marcin Sorry, i think i did not explained my problem enough. I didn't search a function, to split a string into an array of strings. I needed a split of a string, to get multiple Strings, without any array. Thats the code, which do what i searched for. `def f(*args): print(args) if __name__ == '__main__': s = 'str1, str2, str3, str4' f(*(s.split(', '))) ` – knumskull Apr 10 '12 at 17:18
  • @Marcin I have a function, which is defined by following code and i don't want to change this code. `def dirEntries(fileList, subdir=False, *args): '''Example usage: fileList = dirEntries(r'H:\TEMP', False, 'txt', 'py') Only files with 'txt' and 'py' extensions will be added to the list. Example usage: fileList = dirEntries(r'H:\TEMP', True)'''` – knumskull Apr 10 '12 at 18:09
  • @Marcin I know, that this place is not the right place to discuss. I never said, that i dislike lists. I only searched for a solution of my problem and after i found it, i would present the solution here. – knumskull Apr 10 '12 at 22:01

3 Answers3

27

You can split a string by using split(). The syntax is as follows...

stringtosplit.split('whattosplitat')

To split your example at every comma and space, it would be:

s = 'str1, str2, str3, str4'
s.split(', ')
CoffeeRain
  • 4,460
  • 4
  • 31
  • 50
10

A bit of google would have found this..

string = 'the quick brown fox'
splitString = string.split()

...

['the','quick','brown','fox']
tbd
  • 126
  • 5
2

Try:

s = 'str1, str2, str3, str4'
print s.split(',')
JMax
  • 26,109
  • 12
  • 69
  • 88