Main.StringsAndLists History

Hide minor edits - Show changes to markup

February 16, 2010, at 08:47 AM MST by 71.196.160.210 -
Added lines 1-41:

(:source lang=python:)

""" Making lists out of strings and strings out of lists http://openbookproject.net/thinkcs/python/english2e/ch09.html#strings-and-lists """

  1. Python has a command called list that takes a sequence type as an argument
  2. and creates a list out of its elements.

list("Crunchy Frog")

  1. given a list of characters we can join them together to form a string:

import string char_list = list("Frog") print char_list print string.join(char_list, '')

  1. note the second parameter of string.join: it determines which character
  2. to insert between each element of the list.
  3. this way we can easily create comma delmited output:

name_list = ['Asa', 'Mark', 'Adam'] print string.join(name_list, ',')

print string.join(name_list, '**')

  1. the opposite action is possible using string.split:

import string song = "The rain in Spain..." print string.split(song)

  1. this form of string.split splits the string on any whitespace character
  2. string.split has an optional argument which specifies the delimiter.
  3. suppose we are given a comma delimited string such as:

comma_delimited = 'Asa,Mark,Adam'

(:sourceend:)