21

Phase 5 - Category 1: Basic String Handling

Chapter 21 • Beginner

60 min

Phase 5 - Category 1: Basic String Handling

Introduction to Strings

Strings are sequences of characters. In Python, strings are immutable, meaning you can't change them directly - you create new strings.

String Basics

Creating Strings

python.js
s = "Hello"
s = 'World'
s = """Multi-line string"""

String Operations

  • len(s) - length of string
  • s[i] - character at index i
  • s + t - concatenation
  • s * n - repeat string n times

String Methods

  • s.upper() - convert to uppercase
  • s.lower() - convert to lowercase
  • s.strip() - remove whitespace

Key Concepts

  1. Indexing: Access characters by position (0-based)
  2. Immutability: Strings can't be modified in place
  3. Slicing: Extract substrings using [start:end]
  4. Iteration: Loop through characters

Common Patterns

  • Get string length
  • Access first and last character
  • Convert case
  • Concatenate strings
  • Compare strings lexicographically

Hands-on Examples

String Length

# Take string input
s = input("Enter a string: ")

# Get length
length = len(s)
print(f"Length: {length}")

Use len() function to get the number of characters in the string.