Docsity

CPSC 121 (Fall 2011) Lecture Notes: String Functions and Basic Cryptography, Study notes of Computer Science

Partial preview of the text

Download CPSC 121 (Fall 2011) Lecture Notes: String Functions and Basic Cryptography and more Study notes Computer Science in PDF only on Docsity!

Today ...

  • More string functions
  • Characters
  • Basic cryptography (start)

Python string methods

Python provides various methods for working with strings

s.upper()

s.lower()

s.count(s2)

  • Number of occurrences of s2 in s "hello".count("l") returns 2 "hello".count("ll") returns 1

s.find(s2)

  • Returns index of first occurrence of s2 in s, or -1 if not found "hello".find("h") returns 0 "hello".find("l") returns 2 "hello".find("z") returns - "mississippi".find("ss") returns 2

s.replace(s old, s new)

  • Returns a new string where each s old in s is replaced by s new

In Python ord() returns ASCII code, chr() returns character:

ord(’A’) 65

chr(65) ’A’

ord(’a’) 97

chr(97) ’a’

chr(97+1) ’b’

chr(122) ’z’

ord(’\n’) 10

chr(10) ’\n’

chr(97) + chr(98) + chr(99) ’abc’

Characters (cont.)

How can we write a to upper(ch) function?

  • Signature: def to upper(ch)
  • Check that ch is a valid lower-case letter (how?)
  • Subtract 32 from the character and return: 97 (‘a’) - 65 (‘A’)
  • Otherwise return given ch

def to_upper(ch): intval = ord(ch) if intval >= 97 and intval <= 122: return chr(intval - 32) else: return ch