String Introduction#

Start with a three-character string#

"cat"

The conceptual mistake you might make is to think of this as the word cat. True, it has that property. But a string is merely a container of characters strung together. That is, it contains characters, in this case c and a and t.

But it might as well contain a whole book: "In the beginning, God created ..." leading eventually to "... Amen." — a long string indeed.

What do we mean by container?

Envision this 📦 containing this c a t but defined and known by the syntax "cat".

Either the double ("") or single ('') quotation marks act as a sort of wall that instructs the Python interpreter to treat these characters as the contents of a string.

Data Containers in General#

Python has several of container types. Right now we are focusing on strings. But it has lists, dictionaries, sets, tuples, and several others we will not get to. Each has advantages and each has peculiar features.

In any given container type you look for basic things it can do. Some give you the ability to perform all four basic operations on data:

  • C reate data

  • R ead data

  • U pdate data

  • D elete data

or CRUD operations.

Not all container types provide all four features. Nonetheless they all have the ability to create and read the data stored.

Reading from a String#

So how do you read from a string? That is, it’s one thing to get the whole string, but many times you want a particular character or range of characters, not the entire object.

For that you need a window into the container.

What does a window look like?

Well not …

# Nope
"cat"( )

Nor this …

# Yeah, no
"cat"{ }

But this

"cat"[ ]
# where the 'window' square brackets contain an integer

Within that window you put an integer – the index of the character’s location.

For now, just think of getting one character at a time. Because the container’s index values begin with 0:

cat = "cat"
print(cat[0]) # 'c'
print(cat[1]) # 'a'
print(cat[2]) # 't'
print(cat[-1]) # 't'
print(cat[-2]) # 'a'
c
a
t
t
a

That was the barebones basics. But strings consist of far, far more.