Strings and Formatting

Strings and Formatting

Creating Strings

# Single or double quotes
name = "Python"
language = 'Programming'

Multi-line strings

poem = """ Roses are red, Violets are blue, Python is awesome, And so are you! """

String Indexing

text = "Hello"
print(text[0])    # H
print(text[-1])   # o
print(text[1:4])  # ell

String Methods

text = "  Hello, Python!  "

print(text.strip()) # "Hello, Python!" print(text.upper()) # " HELLO, PYTHON! " print(text.lower()) # " hello, python! " print(text.replace("Python", "World")) # " Hello, World! " print(text.split(",")) # [" Hello", " Python! "]

String Formatting

F-Strings (Recommended)

name = "John"
age = 30

print(f"My name is {name} and I am {age} years old")

My name is John and I am 30 years old

With formatting

price = 19.99 print(f"Price: ${price:.2f}") # Price: $19.99

format() Method

name = "Alice"
print("Hello, {}".format(name))  # Hello, Alice

String Slicing

text = "Python"

text[:3] # "Pyt" text[3:] # "hon" text[::2] # "Pto" (every 2nd character) text[::-1] # "nohtyP" (reversed)

Summary

  • Strings are immutable sequences
  • Methods: strip, upper, lower, replace, split
  • F-strings: modern and recommended formatting

Next Lesson

In the next lesson, you'll learn about conditional statements (if/else).

Quiz - Quiz - Strings and Formatting

1. How do you get the length of a string?

2. What does f-string stand for?

3. What is string slicing used for?

Operators