Python Lesson 15: Strings

🐍 Python CourseLesson 15 of 26 · 58% complete

Strings store text. Python has powerful built-in tools for working with strings. Almost every real program uses strings constantly.

String Basics

# Single or double quotes — both work
name = "Alice"
name2 = 'Bob'

# Multi-line string
message = """This is
a multi-line
string"""

# String length
print(len("Hello"))  # 5

# String repetition
print("Ha" * 3)  # HaHaHa

String Indexing and Slicing

text = "Python"
#       012345

print(text[0])     # P
print(text[-1])    # n
print(text[0:3])   # Pyt
print(text[:3])    # Pyt
print(text[3:])    # hon
print(text[::-1])  # nohtyP — reversed!

Essential String Methods

text = "  Hello, World!  "

print(text.upper())        # "  HELLO, WORLD!  "
print(text.lower())        # "  hello, world!  "
print(text.strip())        # "Hello, World!" (remove spaces)
print(text.replace("World", "Python"))  # "Hello, Python!"
print(text.strip().split(", "))  # ["Hello", "World!"]
print("hello" in text.lower())   # True
print(text.strip().startswith("Hello"))  # True
print(text.strip().endswith("!"))        # True
print(text.strip().count("l"))           # 3

f-strings (The Best Way)

name = "Alice"
age = 30
pi = 3.14159

print(f"Hello, {name}!")              # Hello, Alice!
print(f"Age: {age}")                  # Age: 30
print(f"Pi: {pi:.2f}")               # Pi: 3.14
print(f"Upper: {name.upper()}")       # ALICE
print(f"Math: {age * 2}")             # 60

String Join and Split

# Split: string to list
sentence = "Python is awesome"
words = sentence.split(" ")
print(words)   # ["Python", "is", "awesome"]

# Join: list to string
words = ["Python", "is", "awesome"]
result = " ".join(words)
print(result)  # Python is awesome

# Join with different separator
print(", ".join(["Alice", "Bob", "Charlie"]))

🏋️ Practice Task

Build a text analyzer. Ask user to enter any sentence. Print: (1) word count, (2) character count (no spaces), (3) sentence in ALL CAPS, (4) sentence reversed, (5) whether it contains the word “Python”.

💡 Hint: Use split() for words, replace(” “,””) for no-space count, [::-1] for reverse, “python” in text.lower() for check.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *