Python Programming/Strings

This lesson introduces Python string processing.

Objectives and Skills
Objectives and skills for this lesson include:
 * Standard Library
 * String operations

Readings

 * 1)  String (computer science)
 * 2) Python for Everyone: Strings

Multimedia

 * 1) YouTube: Python for Informatics - Chapter 6 - Strings
 * 2) YouTube: Python - Strings
 * 3) YouTube: Python - String Slicing
 * 4) YouTube: Python - String Formatting
 * 5) YouTube: Python Strings Playlist

len function
The len function returns the length (the number of items) of an object.

Output: len(string): 4

Strings
Textual data in Python is handled with str objects, or strings. Strings are immutable sequences of Unicode code points.

Output: Characters: T e s t

Characters by position: string[0]: T string[1]: e string[2]: s string[3]: t

Membership Comparisons
The operators  and   test for membership. evaluates to true if x is a member of s, and false otherwise.

Output: The string contains: a g h i m n o p r s t y

String Methods
Strings implement all of the common sequence operations, along with additional methods such as case validation and conversion.

Output: string: Test string.isalpha: True string.islower: False string.isnumeric: False string.isspace: False string.istitle: True string.isupper: False string.lower: test string.strip: Test string.swapcase: tEST string.title: Test string.upper: TEST

String Parsing
Python substrings are referred to as slices. Slices are accessed using the syntax, with the first character index starting at zero. The slice will include the characters from start up to but not including end. If end is omitted, the slice will include the characters from start through the end of the string. String slices may use negative indexing, in which case the index counts backwards from the end of the string. The find method returns the lowest index in the string where a substring is found within the given slice. Returns -1 if the substring is not found.

Output: Project: Python Programming Page: Strings

String Formatting
String objects have one unique built-in operation: the % operator (modulo). This is also known as the string formatting or interpolation operator. Given format % values (where format is a string), % conversion specifications in format are replaced with zero or more elements of values.

Output: Value: 65.5 Integer: 65 Octal: 101 Hexadecimal: 41 Float: 65.50 Exponent: 6.55e+01 Character: A String: 65.5 Multiple: 65, 101, 41, 65.50, 6.55e+01, A, 65.5

str.format Method
The str.format method uses format strings that contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output.

Output: Decimal: 65 Binary: 1000001 Octal: 101 Hexadecimal: 41 Character: A Float: 65.50 Exponent: 6.55e+01 String: 65.5 Multiple: 65, 1000001, 101, 41, A, 65.50, 6.55e+01, 65.5

String Interpolation
Introduced in Python 3.6, string interpolation formats strings that contain “replacement fields” surrounded by curly braces {}, similar to the str.format method. However, an uppercase or lowercase 'f' is placed before the string to indicate string formatting:

Output:

Tutorials

 * 1) Complete one or more of the following tutorials:
 * 2) * LearnPython
 * 3) ** String Formatting
 * 4) * TutorialsPoint
 * 5) ** Strings
 * 6) * Codecademy
 * 7) ** Strings and Console Output
 * 8) * Wikiversity
 * 9) ** Python/Strings
 * 10) * Wikibooks
 * 11) ** A Beginner's Python Tutorial/Variables, Scripts

Practice

 * 1) Review Python.org: String methods. Create a Python program that asks the user for a line of text containing a first name and last name. Use string methods to parse the line and print out the name in the form last name, first initial, such as   Include a trailing period after the first initial. Ensure that the first letter of each name part is capitalized, and the rest of the last name is lower case. Include error handling in case the user does not enter exactly two name parts. Use a user-defined function for the actual string processing, separate from input and output.
 * 2) Review Python.org: String methods. Create a Python program that asks the user for a line of comma-separated-values. It could be a sequence of test scores, names, or any other values. Use string methods to parse the line and print out each item on a separate line. Remove commas and any leading or trailing spaces from each item when printed. If the item is numeric, display it formatted as a floating point value with two decimal places. If the value is not numeric, display it as is.
 * 3) Review Python.org: String methods. Create a Python program that asks the user for a line of text that contains HTML tags, such as:     Use string methods to search for and remove all HTML tags, and then print the remaining untagged text. Include error handling in case an HTML tag isn't entered correctly (an unmatched ). Use a user-defined function for the actual string processing, separate from input and output.
 * 4) Review Python.org: String methods. Create a Python program that asks the user for a line of text. Then ask the user for the number of characters to print in each line, the number of lines to be printed, and a scroll direction, right or left. Using the given line of text, duplicate the text as needed to fill the given number of characters per line. Then print the requested number of lines, shifting the entire line's content by one character, left or right, each time the line is printed. The first or last character will be shifted / appended to the other end of the string. For example:

Lesson Summary

 * A string is traditionally a sequence of characters, either as a literal constant or as some kind of variable.
 * A string variable may allow its elements to be mutated and the length changed, or it may be fixed (after creation).
 * Python strings are immutable — they cannot be changed.
 * The len function returns the length (the number of items) of an object.
 * Textual data in Python is handled with str objects, or strings. Strings are immutable sequences of Unicode code points.
 * The operators  and   test for membership.   evaluates to true if x is a member of s, and false otherwise.
 * String methods include: isalpha, islower, isnumeric, isspace, istitle, isupper, lower, strip, swapcase, title, and upper.
 * Python substrings are referred to as slices. Slices are accessed using the syntax, with the first character index starting at zero. The slice will include the characters from start up to but not including end. If end is omitted, the slice will include the characters from start through the end of the string.
 * String slices may use negative indexing, in which case the index counts backwards from the end of the string.
 * The find method returns the lowest index in the string where a substring is found within the given slice. Returns -1 if the substring is not found.
 * String objects have one unique built-in operation: the % operator (modulo). This is also known as the string formatting or interpolation operator. Given  (where format is a string), % conversion specifications in format are replaced with zero or more elements of values.
 * The str.format method uses format strings that contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output.

Key Terms

 * counter
 * A variable used to count something, usually initialized to zero and then incremented.


 * empty string
 * A string with no characters and length 0, represented by two quotation marks.


 * format operator
 * An operator, %, that takes a format string and a tuple and generates a string that includes the elements of the tuple formatted as specified by the format string.


 * format sequence
 * A sequence of characters in a format string, like %d, that specifies how a value should be formatted.


 * format string
 * A string, used with the format operator, that contains format sequences.


 * flag
 * A boolean variable used to indicate whether a condition is true.


 * invocation
 * A statement that calls a method.


 * immutable
 * The property of a sequence whose items cannot be assigned.


 * index
 * An integer value used to select an item in a sequence, such as a character in a string.


 * item
 * One of the values in a sequence.


 * method
 * A function that is associated with an object and called using dot notation.


 * object
 * Something a variable can refer to. For now, you can use “object” and “value” interchangeably.


 * search
 * A pattern of traversal that stops when it finds what it is looking for.


 * sequence
 * An ordered set; that is, a set of values where each value is identified by an integer index.


 * slice
 * A part of a string specified by a range of indices.


 * traverse
 * To iterate through the items in a sequence, performing a similar operation on each.

Assessments

 * Flashcards: Quizlet: Python Strings
 * Quiz: Quizlet: Python Strings