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

These lecture notes cover string functions in python, including uppercase and lowercase conversion, counting and finding substrings, and replacing substrings. It also introduces basic cryptography, discussing the concept and examples of encryption algorithms. The notes include examples and exercises for better understanding.

Typology: Study notes

2012/2013

Uploaded on 09/28/2013

noob
noob 🇮🇳

4.4

(25)

105 documents

1 / 6

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Lecture Notes CPSC 121 (Fall 2011)
Today ...
More string functions
Characters
Basic cryptography (start)
S. Bowers 1 of 18
pf3
pf4
pf5

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