Skip to content

Strings (str) · Indexing and Slicing ​

str (String) ​

Definition: A data type for text data, written with single quotes (' ') or double quotes (" ").

Features

  • Can contain letters, numbers and special characters
  • Supports concatenation (+) and repetition (*)
  • Careful! The same symbol behaves differently depending on the data type. Even if it looks like a number, anything inside quotes is a string, so + joins the strings together, and "string" * number repeats it that many times.
python
a = "1000"
b = "100"
name = "Jo"
message = 'Hello, Python!'
phone = "010-1234-5678"

print(a + b)                    # output: 1000100 (joined, not added as numbers)
print(name * 3)                 # output: JoJoJo
print(name + " is here")        # output: Jo is here
print("Ha" * 3)                 # output: HaHaHa
print(len(name))                # output: 2 (string length)
print(name[0])                  # output: J (indexing, the 0th character)

Indexing and Slicing ​

  • Indexing: take out a single value. Indexes start from 0.
  • Slicing: cut out and take several values. In [start:end], the end position is not included (up to end-1).
python
# Indexing example
arr = [10, 20, 30, 40]

print(arr[0])   # prints 10
print(arr[1])   # prints 20

print(arr[-1])  # 40 (the last one)
print(arr[-2])  # 30

s = "hello"     # works on strings too

print(s[0])     # prints h
print(s[1])     # prints e
python
# Slicing example
sold = "5 300"               # Careful! This is a string
sold_mount = int(sold[2:5])  # from index 2 to 4 (5 is not included)
print(sold_mount)            # prints 300

arr = [10, 20, 30, 40, 50]

print(arr[0:3])  # prints [10, 20, 30]
print(arr[:3])   # from the start to index 2
print(arr[2:])   # from index 2 to the end

s = "hello"
print(s[1:4])    # prints ell

arr = [1, 2, 3, 4, 5]
print(arr[::2])  # [1, 3, 5] prints every 2nd item

Summary ​

ConceptSummary
strString data type → text data
IndexingTake out a single value, starting from 0
SlicingCut out several values with [start:end]; the end position is not included

Reference: personal Notion study notes (onboarding course)