tags:

views:

102

answers:

4

I looked in my book and in the documentation, and did this:

a = "hello"
b = a.split(sep= ' ')
print(b)

I get an error saying split() takes no keyword arguments. What is wrong?

I want to have ['h','e','l','l','o'] I tried not passing sep and just a.split(' '), and got ['hello']

+2  A: 

try just:

a = "hello"
b = a.split(' ')
print(b)

notice the difference: a.split(' ') instead of a.split(sep=' '). Even though the documentation names the argument "sep", that's really just for documentation purposes. It doesn't actually accept keyword arguments.

In response to the OP's comment on this post:

"a b c,d e".split(' ') seperates "a b c,d e" into an array of strings. Each ' ' that is found is treated as a seperator. So the seperated strings are ["a", "b", "c,d", "e"]. "hello".split(' ') splits "hello" everytime it see's a space, but there are no spaces in "hello"

If you want an array of letters, use a list comprehension. [letter for letter in string], eg [letter for letter in "hello"]

Wallacoloo
I should have been more specific. I tried that and got ['hello'], I want ['h','e','l','l','o']
Jack S.
+6  A: 

Python allows a concept called "keyword arguments", where you tell it which parameter you're passing in the call to the function. However, the standard split() function does not take this kind of parameter.

To split a string into a list of characters, use list():

>>> a = "hello"
>>> list(a)
['h', 'e', 'l', 'l', 'o']

As an aside, an example of keyword parameters might be:

def foo(bar, baz=0, quux=0):
    print "bar=", bar
    print "baz=", baz
    print "quux=", quux

You can call this function in a few different ways:

foo(1, 2, 3)
foo(1, baz=2, quux=3)
foo(1, quux=3, baz=2)

Notice how you can change the order of keyword parameters.

Greg Hewgill
list() seems to work as well as a for loop. Whats more efficient?
Jack S.
@Jack S.: It depends on what you want to do, but a `for` loop might be the easiest if you just want to iterate through each character. Creating a list involves allocating memory for a list and copying each character, which a `for` loop wouldn't need to do.
Greg Hewgill
+1  A: 

Given a string x, the Pythonic way to split it into individual characters is:

for c in x:
    print c

If you absolutely needed a list then

redundant_list = list(x)

I call the list redundant for a string split into a list of characters is less concise and often reflects C influenced patterns of string handling.

msw
A: 

Try:

a = "hello"
b = list(a)
Zabba