.split() Qeustion
Dave Angel
davea at davea.name
Wed Aug 14 01:35:40 EDT 2013
eschneider92 at comcast.net wrote:
> How can I use the '.split()' method (am I right in calling it a method?) without instead of writing each comma between words in the pie list in the following code? Also, is there a way to use .split instead of typing the apostrophes? Thank you.
>
> import random
> pie=['keylime', 'peach', 'apple', 'cherry', 'pecan']
> print(random.choice(pie))
>
I can't make any sense out of the first sentence. But maybe I can guess
what you're looking for.
The split() method is indeed a method of the str class. It takes an
optional argument for the separator character. By default it uses
whitespace. So if you're trying to specify a series of items, none of
which contain any whitespace, you can readily use split to build your
list:
pie = "keylime peach apple cherry pecan".split()
However, there'd be no way to specify an item called "chocolate
marshmallow". If you need to include whitespace in any item, then you'd
have to use some other separator, like a comma:
pie = "keylime,chocolate marshmallow,peach,apple,cherry,
pecan".split(",")
--
Signature file not found
More information about the Python-list
mailing list