Question 6.6: Creating a List by Parsing a String You need to convert a st......

Creating a List by Parsing a String

You need to convert a string of words separated by some character into an array of strings with each string in the array being one of the words.

Step-by-Step
The 'Blue Check Mark' means that this solution was answered by an expert.
Learn more on how do we answer questions.

Use the split Python string function.

The command split with no parameters separates the words out of a string into individual elements of an array:

>>> “abc def ghi”.split()
[‘abc’, ‘def’, ‘ghi’]

If you supply split with a parameter, then it will split the string using the parameter as a separator. For example:

>>> “abc–de–ghi”.split(‘–‘)
[‘abc’, ‘de’, ‘ghi’]

Discussion

This command can be very useful when you are, say, importing data from a file. The split command can optionally take an argument that is the string to use as a delimiter when you are splitting the string. So, if you were to use commas as a separator, you could split the string as follows:

>>> “abc,def,ghi”.split(‘,’)
[‘abc’, ‘def’, ‘ghi’]

See Also

All the recipes between Recipes 6.1 and 6.11 involve the use of lists.

Related Answered Questions

Question: 6.15

Verified Answer:

Use the for command to iterate over the keys of th...
Question: 6.14

Verified Answer:

Use the pop command, specifying the key for the it...
Question: 6.11

Verified Answer:

Use the Python language feature called comprehensi...
Question: 6.12

Verified Answer:

Use a Python dictionary. Arrays are great when you...
Question: 6.13

Verified Answer:

Use the Python [] notation. Use the key of the ent...
Question: 6.10

Verified Answer:

Use the [:] Python language construction. The foll...
Question: 6.9

Verified Answer:

Use the sort Python language command: >>&...
Question: 6.7

Verified Answer:

Use the for Python language command: >>&g...
Question: 6.2

Verified Answer:

Use the [] notation to access elements of a list b...