Jack S.
Jack S.

Reputation: 2793

what's wrong with the way I am splitting a string in python?

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']

Upvotes: 7

Views: 2269

Answers (4)

Ponkadoodle
Ponkadoodle

Reputation: 5957

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"], or just use the list constructor as in list("hello").

Upvotes: 5

Zabba
Zabba

Reputation: 65467

Try:

a = "hello"
b = list(a)

Upvotes: 0

msw
msw

Reputation: 43487

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.

Upvotes: 2

Greg Hewgill
Greg Hewgill

Reputation: 993055

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.

Upvotes: 6

Related Questions