CMU 15-110: Principles of Computing
Strings: Part 1
- String Literals
- Some String Constants
- Some String Operators
- Looping over Strings
- Strings are Immutable
- Some String-related Functions
- Some String Methods
- Basic File IO
- String Literals
- Four kinds of quotes
print('single-quotes') print("double-quotes") print('''triple single-quotes''') print("""triple double-quotes""")
- Four kinds of quotes
- Some String Constants
import string print(string.ascii_letters) # abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ print(string.ascii_lowercase) # abcdefghijklmnopqrstuvwxyz print(string.ascii_uppercase) # ABCDEFGHIJKLMNOPQRSTUVWXYZ print(string.digits) # 0123456789 print(string.punctuation) # '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' print(string.whitespace) # space + tab + linefeed + return + ...
- Some String Operators
- String + and *
print('abc' + 'def') print('abc' * 3) print('abc' + 3) # error - The in operator
print('ring' in 'strings') print('wow' in 'amazing!') print('Yes' in 'yes!') print('' in 'No way!') - String indexing and slicing
- Indexing a single character
s = 'abcdefgh' print(s) print(s[0]) print(s[1]) print(s[len(s)-1]) print(s[len(s)]) # crashes (string index out of range) - Negative indexes
s = 'abcdefgh' print(s) print(s[-1]) print(s[-2]) print(s[-len(s)]) print(s[-len(s)-1]) # crashes (string index out of range) - Slicing a range of characters
s = 'abcdefgh' print(s) print(s[0:4]) print(s[2:4])
- Indexing a single character
- String + and *
- Looping over Strings
- "for" loop with indexes
s = 'abcd' for i in range(len(s)): print(i, s[i]) - "for" loop without indexes
s = 'abcd' for c in s: print(c)
- "for" loop with indexes
- Strings are Immutable
- You cannot change strings! They are immutable.
s = 'abcde' s[2] = 'z' # Error! Cannot assign into s[i] - Instead, you must create a new string
s = 'abcde' s = s[:2] + 'z' + s[3:] print(s)
- You cannot change strings! They are immutable.
- input(), str(), and len()
name = input('Enter your name: ') print('Hi, ' + name + '. Your name has ' + str(len(name)) + ' letters!') - chr() and ord()
print(ord('A')) # 65 print(chr(65)) # 'A' print(chr(ord('A')+1)) # ?
- String tests
s.isalpha() True if s only contains letters A-Z,a-z s.isdigit() True if s only contains digits 0-9 s.isspace() True if s only contains whitespace (spaces, tabs, newlines) s.islower() True if the letters in s are all lowercase (a-z) s.isupper() True if the letters in s are all uppercase (A-Z) - String edits
s.lower() Returns a copy of s in lowercase s.upper() Returns a copy of s in uppercase
For example:print('This is nice. Yes!'.lower()) print('So is this? Sure!!'.upper())
# Note: As this requires read-write access to your hard drive,
# this will not run in the browser in Brython.
def readFile(path):
# This makes a very modest attempt to deal with unicode if present
with open(path, 'rt', encoding='ascii', errors='surrogateescape') as f:
return f.read()
def writeFile(path, contents):
with open(path, 'wt') as f:
f.write(contents)
contentsToWrite = 'This is a test!\nIt is only a test!'
writeFile('foo.txt', contentsToWrite)
contentsRead = readFile('foo.txt')
assert(contentsRead == contentsToWrite)
print('Open the file foo.txt and verify its contents.')