Programming in Python

Strings

Gerald Senarclens de Grancy

Terminology

  • Datatype
  • Char array vs. string
  • Immutable
    • No assignment to elements allowed
    • Methods return new objects
  • Function signature

Sequence Data Types

Index, membership, size, slicing and iteration

  • Can be described by a start point and an endpoint
  • Support the membership operator (in) and the size function (len())
  • Elements can be selected with their index in square brackets
  • Indices start at 0
  • Slicing: extract part of a sequence as a new sequence
  • Sequences are iterable

Library

  • Collection of pre-built code we can use
  • Using them avoids duplicate work
  • They are usually designed by professionals
  • Standard library vs. third party libraries

Built-in functions (BIFs) are always available

...we again and again avoid doing complicated work and instead find simpler solutions - often relying on library facilities. That's the essence of programming: the continuing search for simplicity.

Bjarne Stroustrup

Google Summer of Code

Python Strings

'text', "", '''''', """"""

s.lower() -> str
s.split([sep[, maxsplit]]) -> list of strings
s.upper() -> str
...

Example - String Operations

#!/usr/bin/env python3

a_string = 'What a beautiful snake!'
a_string.upper()
print(a_string)
a_string = a_string.upper()
print(a_string)

print()
print(a_string.split())
a_string = 'Steve, Paul, Susan, Anna, Peter, Amy'
print(a_string.split(', '))

Visualize execution

Substrings

  • The first element of any sequence has the index 0
  • A second index points to the element after a slice
  • Start and end are available by skipping an index

Example - Index and Slicing

#!/usr/bin/env python3

a_string = "What a beautiful snake!"
char = a_string[0]
char = a_string[1]
char = a_string[-1]
char = a_string[-3]
substring = a_string[1:5]
substring = a_string[1:-3]
substring = a_string[:-2]
substring = a_string[-2:]
result = a_string[::2]

Visualize execution

f-Strings

Defined in PEP 498 - Literal String Interpolation

f'text {var} text', f"", f'''''', f""""""

#!/usr/bin/env python3

name = 'Pat'
points = 3
print(f'{name} received {points} points.')
value = 3.1473
s = f'The formatted value is {value:.2f}.'
print(s)

Visualize execution

Format Specification Mini-Language

Python 3 Video Tutorial - Strings

Python 3 Video Tutorial - String Formatting

For Loops

Iterate over the elements of a sequence

Each time the body of a for loop runs, a variable is set to the next element of a sequence

Example

#!/usr/bin/env python3

A_STRING = 'What a beautiful snake!'
for char in A_STRING:
    print(char)
for index, char in enumerate(A_STRING):
    print(f'{index:2}: {char}')

Visualize execution

range(.)

range(stop) -> range object
range(start, stop[, step]) -> range object

Example

#!/usr/bin/env python3

total = 0
for i in range(5):
    total += i

for _i in range(5):
    print("Repeated action")

sum_even = 0
for i in range(10, 0, -2):
    sum_even += i

Visualize execution

Python 3 Video Tutorial - For Loops

Reading Files

  1. Open the file with open(.)
  2. Read the file with read(), readline(), readlines() or iterate over its content
  3. Close the file with close() or implicitly (end of with)

The recommended way to read files is

with open(filename, encoding='utf-8') as f:
    for line in f:
        print(line, end="")

Note that filename must contain a the name of a readable file (string)

Python 3 Video Tutorial - Reading and Writing Files

Summary

  • Elements of a sequence are referenced by indices
  • Where do indices start? Why?
  • Which data types do we know by now?
  • Built-in functions
    • enumerate(.), open(.), range(.)
  • Standard library functions
    • s.lower(), s.upper(), ...

Questions
and feedback...