// Basics
Strings — The Full Picture
The idea!
You've covered a lot. Variables, strings, methods, input, output.
This is your reference. Everything in one place.
Come back here whenever you need a reminder.
What is a String
A string is text. Any sequence of characters wrapped in quotes.
name = "Bull"
empty = ""
phrase = "Hello, world!"
Strings can be combined with +:
print("Red" + "Horn") # RedHorn
print("Red" + " " + "Horn") # Red Horn
Indexing
Every character has a position. Indexing starts at 0.
name = "Bull"
# B u l l
# 0 1 2 3
print(name[0]) # B
print(name[-1]) # l — last character
Slicing
Extract a range of characters with [start:stop]. Start included, stop not.
name = "RedHorn"
print(name[0:3]) # Red
print(name[3:]) # Horn
print(name[:3]) # Red
print(name[-4:]) # Horn
Methods — Transform
name = " Bull "
print(len("Bull")) # 4
print(name.strip()) # Bull
print(name.strip().upper()) # BULL
print(name.strip().lower()) # bull
print("bull horn".replace("horn", "red")) # bull red
Methods — Search & Structure
message = "Hello Bull"
print("Bull" in message) # True
print(message.find("Bull")) # 6
print(message.count("l")) # 3
print(message.startswith("Hello")) # True
print(message.endswith("Bull")) # True
print(message.split()) # ['Hello', 'Bull']
Print Formatting
name = "Bull"
age = 25
# f-strings
print(f"My name is {name} and I am {age} years old.")
# sep and end
print("Red", "Horn", sep="-") # Red-Horn
print("Hello", end=" ")
print("Bull") # Hello Bull
# Number formatting
price = 3.14159
print(f"Price: {price:.2f}") # Price: 3.14
Input
# input() always returns a string
name = input("Enter your name: ")
# Convert if you need a number
age = int(input("Enter your age: "))
height = float(input("Enter your height: "))
print(f"Hi {name}, you are {age} years old.")
Common Mistakes
- Quotes must match — open and close with the same type
- Indexing starts at
0, not1 - Going beyond the last index →
IndexError - Methods return a new string — reassign to keep the change
- Can't add a string and a number — use
str()or an f-string - Strings are case sensitive —
"Bull"and"bull"are not the same
What you should understand now
- Strings are text — and text is data
- Every character has a position
- Methods transform, search, and structure strings
- f-strings are the cleanest way to format output
- input() always returns a string — convert when needed
// resources
// 0 comments
// No comments yet. Be the first.
// leave a comment