开发者

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 argu开发者_如何学Cments. What is wrong?

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


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.


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").


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.


Try:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜