Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

split

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

like image 973
Jack S. Avatar asked Oct 10 '10 03:10

Jack S.


People also ask

What is best way to split a string in Python?

Python String split() Method The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

How do you split a string evenly in Python?

Python split() method is used to split the string into chunks, and it accepts one argument called separator. A separator can be any character or a symbol. If no separators are defined, then it will split the given string and whitespace will be used by default.

Does split modify the original string?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.


1 Answers

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.

like image 176
Greg Hewgill Avatar answered Sep 29 '22 07:09

Greg Hewgill