Strings

Introduction

Defining strings

x = "Hello"

Can type hint a string

x: str = "Hello"

String pool

Strings stored in a pool. If 100 variables are of the same string, not stored 100 times.

Immutability of strings

Can’t do the following.

x = "Hello"
x[2] = "b"

For security (if not, presumably copy on write could be implemented).

Operations on strings

string strip

concatenation

Iterating over a string

Can treat strings like an array

Following prints out each character on a new row.

x = "Hello"
for ch in x:
    print(ch)

SORT

if define a string, is unicode. can convert to bytes

"my string".encode() to get the bytes which encode the string

b"b string".decode() to convert byte string into unicode string

eg for hebrew characters

"hellò".encode()
b'\xd7\xa9\xd7\x9c\xd7\x95\xd7\x9d \xd7\xa2\xd7\x95\xd7\x9c\xd7\x9d'.decode()

Printing strings

print

x = "apple"
print(x)

repl

x = "apple"
repl(x)

string.format()

F strings

x = "apples"
y = 2
print(f"I eat {y} {x}")

% operators

Using commas in print()

x = "apple"
y = banana"
print(a, b)