0
votes

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')
3
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
@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
@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
@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

3 Answers

25
votes

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(', ')
8
votes

A bit of google would have found this..

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

...

['the','quick','brown','fox']
2
votes

Try:

s = 'str1, str2, str3, str4'
print s.split(',')