0% found this document useful (0 votes)
2 views

03.python.04.stringslistsdictionaries

The document provides an overview of strings, lists, and dictionaries in programming, detailing their definitions, properties, and operations. Strings are immutable sequences of characters, while lists are mutable sequences of ordered elements, and dictionaries are mutable mappings of keys to values. It also includes examples of operations and methods applicable to each data type.

Uploaded by

dznz1999
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

03.python.04.stringslistsdictionaries

The document provides an overview of strings, lists, and dictionaries in programming, detailing their definitions, properties, and operations. Strings are immutable sequences of characters, while lists are mutable sequences of ordered elements, and dictionaries are mutable mappings of keys to values. It also includes examples of operations and methods applicable to each data type.

Uploaded by

dznz1999
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

strings

strings
definition

• an immutable (unchangeable) sequence of characters


• accessed by offset (position)
• its characters are "code point ordinals" in the
character set (characters are strings of length 1)
• written as a sequence of characters in quotes
• "python's string"
Some string constant escape codes
• 'python"s string' \t tab
• 'python\'s string' \n newline
\0 Null
• """this is a multi \\ backslash (\)
\' single quote
line string""" \" double quote

strings

index/position

0 1 2 3 4 5 6 7 8 9 10

t h i s i s i t !

seq[1]
seq[-1]
seq[-2]
strings

index/position

0 1 2 3 4 5 6 7 8 9 10

t h i s i s i t !

seq[1] # => 'h'


seq[-1] # => '!'
seq[-2] # => 't'
strings

index/position

0 1 2 3 4 5 6 7 8 9 10

t h i s i s i t !

slice seq[1]
seq[-1]
seq[-2]
seq[0:3]
seq[3:]
seq[:5]
strings

index/position

0 1 2 3 4 5 6 7 8 9 10

t h i s i s i t !

slice seq[1] # => 'h'


seq[-1] # => '!'
seq[-2] # => 't'
seq[0:3] # => 'thi'
seq[3:] # => 's is it!'
seq[:5] # => 'this '
strings

index/position

0 1 2 3 4 5 6 7 8 9 10

t h i s i s i t !

slice seq[1] # => 'h'


seq[-1] # => '!'
seq[-2] # => 't'
seq[0:3] # => 'thi'
seq[3:] # => 's is it!'
seq[:5] # => 'this '
sequence operations
strings, lists, tuples, bytes and bytearray

x in seq # => True /False


x not in seq # => True /False
seq1 + seq2 # concatenation
seq * num, num * seq # repetition
seq[i] # index
seq[i:j] # slice
len(seq) # length
min(seq) # minimum
max(seq) # maximum
iter(seq) # iteration
for x in seq: # iteration
[expr for x in seq] # iteration
string methods

seq.capitalize() seq.isalpha() seq.ljust(width[, fillchar]) seq.rsplit(sep=None, maxsplit=-1)

seq.casefold() seq.isascii() seq.lower() seq.rstrip([chars])

seq.center(width [,fill]) seq.isdecimal() seq.lstrip([chars]) seq.split(sep=None, maxsplit=-1)

seq.count(sub [,start[, end]]) seq.isdigit() seq.maketrans(x[, y[, z]]) seq.splitlines(keepends=False)

seq.encode(encoding[, errors]) seq.isidentifier() seq.partition(sep) seq.startswith(prefix[, start[, end]])

seq.endswith(suffix [,start[, end]]) seq.islower() seq.removeprefix(prefix, /) seq.strip([chars])

seq.expandtabs([tabsize]) seq.isnumeric() seq.removesuffix(suffix, /) seq.swapcase()

seq.find(sub[, start[, end]]) seq.isprintable() seq.replace(old, new, count=-1) seq.title()

seq.format(*args, **kwargs) seq.isspace() seq.rfind(sub[, start[, end]]) seq.translate(table)

seq.format_map(mapping, /) seq.istitle() seq.rindex(sub[, start[, end]]) seq.upper()

seq.index(sub[, start[, end]]) seq.isupper() seq.rjust(width[, fillchar]) seq.zfill(width)

seq.isalnum() seq.join(iterable) seq.rpartition(sep)

format methods search methods split/join methods

in all calls that return a string result, the result is a new string (because strings are immutable)
string methods
immutable

seq = "this is a test"


print(seq.title())
string methods
immutable

seq = "this is a test"


print(seq.title())

'This Is A Test'
string methods
immutable

seq = "this is a test"


print(seq.title())

'This Is A Test'

print(seq)
string methods
immutable

seq = "this is a test"


print(seq.title())

'This Is A Test'

print(seq)

'this is a test'
string methods
immutable

seq = "this is a test"


seq = seq.title()
print(seq)

'This Is A Test'
strings
operations

• strings support all sequence operations, plus some


specific methods
• supports formatting % expressions
'_how_'.format(_variable_)
'%s is a sentence of %d
'%.2f'.format(s,dim,value)
lists
lists
definition

• a mutable sequence of ordered elements


• accessed by offset (position)
• written as a sequence of comma-separated values,
enclosed in square brackets
• []
• [1, 4, -5, 8]
• ["dog", "cat", "horse"]
• [0, "home", 2.50]
• [12, ["a", "c", "g", "t"], ""]
lists & strings

• similarity:
• sequences of elements and characters, same operators,
same access type (by index)

• differences:
• strings are sequences of characters (homogeneous),
lists are sequences of any type of elements
• lists are mutable, strings are immutable
sequence operations
strings, lists, tuples, bytes and bytearray

x in seq # => True /False


x not in seq # => True /False
seq1 + seq2 # concatenation
seq * num, num * seq # repetition
seq[i] # index
seq[i:j] # slice
len(seq) # length
min(seq) # minimum
max(seq) # maximum
iter(seq) # iteration
for x in seq: # iteration
[expr for x in seq] # iteration
mutable sequence operations
strings, lists, tuples, bytes and bytearray

seq[i] = el # index assignment: change item i


seq[i:j] = el # slice assignment
seq[i:j:k] = el # slice assignment, with stride k
del seq[i] # index deletion
del seq[i:j] # slice deletion
del seq[i:j:k] # slice deletion, with stride k
list methods

lst.append(el) lst.count(el)

lst.extends(it) lst.remove(el) ***

lst.sort(key=None, reverse=False) lst.pop([pos])

lst.reverse() lst.clear()

lst.index(el[,i[,j]]) lst.copy()

lst.insert(pos, el)

all calls modify the list in-place


list methods
immutable

lst = [1, 2, 3]
print(lst)
list methods
immutable

lst = [1, 2, 3]
print(lst)

[1, 2, 3]
list methods
immutable

lst = [1, 2, 3]
print(lst)

[1, 2, 3]

lstdup = lst.copy()
lst.append(6)
print(lst, lstdup)
list methods
immutable

lst = [1, 2, 3]
print(lst)

[1, 2, 3]

lstdup = lst.copy()
lst.append(6)
print(lst, lstdup)
[1, 2, 3, 6] [1, 2, 3]
list methods
immutable

lst = [1, 2, 3]
print(lst)

[1, 2, 3]

lstdupagain = lst
lst.append(6)
print(lst, lstdupagain)
list methods
immutable

lst = [1, 2, 3]
print(lst)

[1, 2, 3]

lstdupagain = lst
lst.append(6)
print(lst, lstdupagain)
[1, 2, 3, 6] [1, 2, 3, 6]
list of items from a string

seq = "this is a sentence"

words = seq.split(" ")


print(words)
list of items from a string

seq = "this is a sentence"

words = seq.split(" ")


print(words)

['this', 'is', 'a', 'sentence']


list of items from a string

seq = "1, 3, -3, 0, 4, 20, -1"

values = seq.split(",")
print(values)
list of items from a string

seq = "1, 3, -3, 0, 4, 20, -1"

values = seq.split(",")
print(values)

['1', ' 3', ' -3', ' 0', ' 4', ' 20', ' -1']
list of items from a string

seq = "1, 3, -3, 0, 4, 20, -1"

values_str = seq.split(",")
values_int = []
for val in values_str:
values_int.append(int(val))

print(values_int)
list of items from a string

seq = "1, 3, -3, 0, 4, 20, -1"

values_str = seq.split(",")
values_int = []
for val in values_str:
values_int.append(int(val))

print(values_int)
[1, 3, -3, 0, 4, 20, -1]
list of items from a string

seq = "1, 3, -3, 0, 4, 20, -1"

values_str = seq.split(",")
values_int = [int(val) for val in values_str]

print(values_int)
list of items from a string

seq = "1, 3, -3, 0, 4, 20, -1"

values_str = seq.split(",")
values_int = [int(val) for val in values_str]

print(values_int)
[1, 3, -3, 0, 4, 20, -1]
string <-> lists

seq = "this is a string"


lst = list(seq)

print(lst)
string <-> lists

seq = "this is a string"


lst = list(seq)

print(lst)
['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ',
's', 't', 'r', 'i', 'n', 'g']
string <-> lists

lst = [1, 2, 3, 4]
lststr = [str(x) for x in lst]

print(lststr)
string <-> lists

lst = [1, 2, 3, 4]
lststr = [str(x) for x in lst]

print(lststr)
['1', '2', '3', '4']
string <-> lists

lst = [1, 2, 3, 4]
lststr = [str(x) for x in lst]

print(lststr)
['1', '2', '3', '4']

seq = "".join(lststr)
print(seq)
string <-> lists

lst = [1, 2, 3, 4]
lststr = [str(elem) for elem in lst]

print(lststr)
['1', '2', '3', '4']

seq = "".join(lststr)
print(seq)
'1234'
string <-> lists

lst = [1, 2, 3, 4]
lststr = [str(elem) for elem in lst]

print(lststr)
['1', '2', '3', '4']

seq = "".join(lststr)
print(seq)
'1234' seq = "".join(str(elem) for elem in lst]
dictionaries
dictionary
definition

• mutable (changeable) mapping of elements


• accessed by key (not position)
• unordered tables that map keys to values
• keys: immutable type
• values: any type
• Examples:
• empty dictionary: {}
• DNACOMP = {'A':'T', 'C':'G', 'G':'C', 'T':'A'}
• basefreq = {'A': 6, 'C': 2, 'G': 4, 'T': 6}
• info = {'fname':['mary', 'jane'], 'lname': ['white']}
dictionary operations

d[k] # retrieves element by key k


d[k] = x # creates or updates element for key k
del d[k] # removes element by key
len(d) # number of keys
k in d # => True /False
k not in d # => True /False
iter(d) # iteration
for k in d: # iteration
dictionary methods

d.keys() d.get(k[, default])

d.values() d.setdefault(k, [, default])

d.items() d.popitem()

d.clear() d.pop(k [, default]) ***

d.copy()

d.update(dx) k in d

for k in d

all calls modify the list in-place


dictionary
example

H2B = {"0": "0000", "1": "0001", "2": "0010", "3":


"0011", "4": "0100", "5": "0101", "6": "0110", "7":
"0111", "8": "1000", "9": "1001", "A": "1010", "B":
"1011", "C": "1100", "D": "1101", "E": "1110", "F":
"1111"}

You might also like