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')
4
  • 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? Commented Mar 14, 2012 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(', '))) Commented Apr 10, 2012 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)''' Commented Apr 10, 2012 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. Commented Apr 10, 2012 at 22:01

3 Answers 3

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(', ')
Sign up to request clarification or add additional context in comments.

Comments

10

A bit of google would have found this..

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

...

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

1 Comment

The default delimiter is <space>.
2

Try:

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

2 Comments

Would someone care explaining why I was downvoted so that I could learn from my mistakes?
No explication, AND answering a help vampire.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.