CIS 111 Strings, formatting

Objectives

  • Use Python string methods
  • Format strings and output

Strings

  • Strings are a sequence of characters.
  • Strings are delimited using ' or ". Examples: "Hello", 'world'
  • Strings can be joined (concatenated): "Hello" + " " + "world"
  • The * operator can be used to create multiple runs of a string: "abc" * 3 == "abcabcabc"
  • You can get the length of a string: len("Hello") == 5
  • len("Hello world!") == 12 # spaces and other punctuation count as characters
  • You can select a substring of a string using the start index and end index + 1
    • "Python"[3] == "h"
    • "Python"[:2] == "Py" # start index 0 is assumed
    • "Python"[2:] == "thon" # end index 1 past end is assumed
    • "01234567890"[3:2] == "" # end index is before start index
    • "01234567890"[3:5] == "34"
    • "01234567890"[3:-2] == "345678" # -2 specifies 2 from the end
  • Combination: "01234567890"[3:5] * 4 == "34343434"
  • Quotes can be used inside a string by using a different type of quote than the delimiter: "That's mine"
  • Quotes can be used inside a string by escaping them using a \: 'That\'s mine'
  • You can put newlines in a string using the \n sequence: "1\n2\n3\n"

String methods

Strings have many available methods. Some of the more commonly used ones are:

  • "python".capitalize() == "Python"
  • "pYtHOn".upper() == "PYTHON"
  • "pYtHOn".lower() == "python"
  • "pYtHOn".casefold() == "python"
  • "Python".center(10, "*") == "**Python**"
  • "Python".ljust(10,"*") == "Python****"
  • "Python".rjust(10,"*") == "****Python"
  • "abracadabra".count("a") == 5
  • "abracadabra".count("ab") == 2
  • "Python".endswith("on") == True
  • "Python".endswith("in") == False
  • "Python".startswith("Py") == True
  • "Python".startswith("py") == False
  • "favorite".find("or") == 3
  • "favorite".find("bob") == -1
  • ("or" in "favorite") == True # NOT a method, "in" is an operator
  • ("bob" in "favorite") == False # NOT a method, "in" is an operator
  • "Bob".replace("B","T").replace("b","m")
  • "CIS,111,A-1374,3.0".split(",") == ['CIS', '111', 'A-1374', '3.0']

String formatting (printf style)

Strings in Python can be formatted using the % operator.

  • The basic syntax is: formatString % values
  • The format string contains conversion specifiers that are filled in with values from the list that follows.
  • Conversion specifiers start with a % and end with a character specifying the conversion type. In between the two may be values specifying width, precision, etc.
  • Between the % and the conversion type you can specify modifiers such as width of field and digits of precision after a decimal point.
  • Example: ("Your ID number is %d" % 16) == "Your ID number is 16"
  • Example: ("Your ID number is %04d" % 16) == "Your ID number is 0016"
  • Example: ("Your rate is %f" % 23.48) == "Your rate is 23.480000"
  • Example: ("Your rate is %.2f" % 23.48) == "Your rate is 23.48"
  • Example: ("Your rate is %06.1f" % 23.48) == "Your rate is 0023.5"
  • Example: ("You are programming in %s" % "Python") == "You are programming in Python"
  • If there are multiple arguments, they should be supplied as a "tuple"
  • Example: "The name of the school is %s %s" % ("Kishwaukee", "College")
  • You can also supplied named arguments using a "dict" (dictionary).
  • "The name of the school is %(first)s %(last)s" % {"last":"College", "first":"Kishwaukee"}
  • See the Python documentation for additional examples and more detail.

String formatting (format method)

Strings in Python can also be formatted using the format method.

  • The basic syntax is: string.format(argumentList)
  • The string contains embedded {#}, where # is a digit specifying which argument should be substituted.
  • Example: "The name of the school is {0} {1}".format("Kishwaukee", "College")
  • You can also use argument names for the substitution.
  • Example: "The name of the school is {fn} {ln}".format(fn="Kishwaukee", ln="College")
  • Field width, data type, alignment, and more can also be specified. That is beyond these notes.
  • See the Python documentation for additional examples and more detail.