Introduction to Problem Solving and Programming in Python http://cis-linux1.temple.edu/~tuf80213/courses/temple/cis1051/ Overview
• Strings • The string type (str) • Operations and escape characters • String formatting • String functions • Converting strings to lists • Dictionaries
2 Strings
• A string is a sequence of characters • Created by enclosing character in single or double quotation marks name = 'John Smith' • A string can span multiple lines by using the triple quote
greeting = '''Hello. My name is John Smith'''
3 Strings
• Strings are immutable • Whenever a string is used in an operation, the original string remains unchanged and a new string is returned • When we perform string operations, a new string is created 'Hello' + ' World!' # Takes 2 strings and build the new string Hello World! • To 'update' a string, reassign the newly created string to the original variable name = 'John' name += " Smith" print (name) # John Smith
4 Strings
• A string is a sequence of characters, and can be operated on in a similar manner to other sequences • Python does not have a character type • A single character is a string sequence of size 1 • To access an individual character in a string, use [] along with a character index • The index of the first character is 0 • Slicing can be performed by using variations of [:]
5 Strings
• In addition to printable characters, strings can contain escape characters • Escape characters are preceded with a backslash, \ • These tell Python to not to print the character, but instead perform the action it represents
6 List of escape characters
Escape character Meaning \\ Backslash \' Single quote \" Double quote \a Bell \b Backspace \f Formfeed \n Linefeed (new line) \r Carriage return \t Horizontal tab \v Vertical tab \ooo ASCII character with octal value ooo
\xhh ASCII character with octal value hh 7 String formatting
• Strings can be formatted by replacing tokens in the string with the values of expressions • Uses the % operator along with a tuple containing the values • E.g. verse = '%d bottles of beer on the %s.' % (98 + 1, 'wall') print(verse) # 99 bottles of beer on the wall.
8 Common string formatting types
Type Meaning %s String %c Character %d Decimal integer (base 10) %b Binary %e Exponent
9 Common string functions
Function Use X.lower(), X.upper() Returns a lower or uppercase version of the string X.strip() Returns a version of the string with whitespaces removed from the beginning and end X.isalpha(), X.isdigit(), Tests whether a string is any of the various character types X.isspace() X.startswith('other'), Tests if X starts or ends with the string argument X.endswith('other') X.find('other') Returns the index of the first instance where other is found in X, and -1 if not found X.replace('old', 'new') Returns a new string where all instance of old have been replaced by new X.split() Returns a list of substrings based on the delimiter argument, or space if none specified X.join() Creates a string from a list argument using X as the delimiter
10 The split() function
• The str class defines a split() function that tokenizes a string and returns a list of those tokens (words) • The default delimiter is whitespace (e.g. space character) • You can specify any string as a delimiter
11 The split() function
• Usage my_string = "This is a string" print(my_string.split()) # ['This', 'is', 'a', 'string']
my_string = "Comma,delimited,string" print(my_string.split(",")) # ['This', 'is', 'a', 'string']
my_string = "Comma,delimited,string" print(my_string.split(",", 1)) # ['Comma', 'delimited,string']
12 Reading multiple values from input()
• Using split(), multiple values can be read from an input() statement first, last = input("Enter your first and last name").split() • Each element in the tuple is a string • To change the type, use map() • Case study: Simple adder • Algorithm • Read two values from a single input statement • Split and convert the values • Add both inputs and print the resulting value
13 Solution
x, y = map(int, input("Enter two values to be added: ").split()) print("Answer: ", x + y)
14 Dictionaries
• A dictionary is a collection of key-value data pairs • A value can be any type of Python object • A key must meet the following criteria • Must be immutable (lists, for example, cannot be keys) • Must be unique within a dictionary
15 Dictionaries
• A dictionary is a collection of key-value data • A value can be any type of Python object • A key must meet the following criteria • Must be immutable (lists, for example, cannot be keys) • Must be unique within a dictionary
16 Dictionaries
• Syntax • Each key is separated from its corresponding value by a colon 'name' : 'Mike' • Each key-value pair is separated by commas and enclosed in curly braces {'name': 'Mike', 'age': 24, 'height': 7.2}
17 Modifying dictionary data
bio = {'name': 'Mike', 'age': 24, 'height': 7.2}
print(bio['name']) # Read a value bio['height'] = 6.0 # Change a value bio['year'] = 'Freshman' # Add a new key-value pair del bio['age'] # Delete a key-value pair
18 Dictionary function
• In addition to some sequence functions (such as cmp() and len()) dictionaries have specific functions
Function Description X.clear() Removes all elements from the dictionary X.has_key(key) Tests if a key-value pair matching the provided key is in the dictionary X.keys(), X.values() Returns a list of key or values from the dictionary X.items Returns a list of tuples of the key-value pairs contained in the dictionary
19