6. Working with Strings
Level: BeginnerDuration: 28m
What Are Strings?
Strings are used to store text in Python. Anything inside quotes is treated as a string.
python
name = "Chrise"
message = 'Hello, Python!'
quote = "Python is awesome!"💡 Use single quotes `'` or double quotes `"`—they both work!
Multiline Strings
Use triple quotes (`'''` or `"""`) when writing long or multi-line text.
python
bio = """
Hi, I'm learning Python.
This is a multiline string.
"""Accessing Characters (Indexing)
Strings are like arrays of characters. Each character has an index starting from 0.
python
text = "Python"
print(text[0]) # P
print(text[3]) # hExtracting Parts of a String (Slicing)
You can extract a part of a string using slicing.
python
word = "Programming"
print(word[0:4]) # Prog
print(word[:6]) # Progra
print(word[3:]) # gramming
print(word[-3:]) # ingString Formatting
You can combine variables with strings using f-strings (recommended).
python
name = "Bella"
age = 22
print(f"My name is {name} and I am {age} years old.")Useful String Methods
Python has built-in functions to transform text easily.
| Method | Description | Example |
|---|---|---|
| upper() | Convert to uppercase | "hello".upper() → "HELLO" |
| lower() | Convert to lowercase | "HELLO".lower() → "hello" |
| title() | Capitalize each word | "python course".title() |
| strip() | Remove spaces | " hello ".strip() |
| replace() | Replace text | "I like JS".replace("JS", "Python") |
| split() | Split into list | "a,b,c".split(",") |
Escape Characters
Use escape sequences to handle quotes or special characters inside strings.
python
sentence = "She said, \"Python is fun!\""
new_line = "First line\nSecond line"String Concatenation
You can join strings together using `+` or f-strings.
python
first = "Hello"
second = "World"
print(first + " " + second)
print(f"{first} {second}")Mini Project Step
Update your bank_account.py file: Add a welcome message that uses string formatting to display the account holder name and bank name. Use at least two string methods like `.upper()` or `.replace()`.