TOPIC 2: Variables, Data Types & Operators

4. Strings and Formatting

What are Strings?

Strings are sequences of characters enclosed in quotes. They are used to represent text in Python. Strings can be enclosed in either single quotes (') or double quotes (").

  • Creating Strings:

name = 'Alice'
greeting = "Hello, " + name  # Concatenation
print(greeting)  # Output: Hello, Alice

String Formatting: Python provides several ways to format strings. You can use f-strings (available in Python 3.6+) or the .format() method.

Example 1: Using f-strings


name = "Alice"
age = 30
print(f"Hello, {name}! You are {age} years old.")  # Output: Hello, Alice! You are 30 years old.

Example 2: Using .format()


name = "Alice"
age = 30
print("Hello, {}! You are {} years old.".format(name, age))  # Output: Hello, Alice! You are 30 years old.