← Back to Chapters

Python Strings

? Python Strings

⚡ Quick Overview

A string in Python is a sequence of characters enclosed in single quotes ('Hello') or double quotes ("Hello"). It can include letters, numbers, spaces, and special symbols.

Strings are one of the most commonly used data types in Python, especially for user interaction, text processing, file handling, and displaying messages on the screen.

? Key Concepts

  • Strings are sequences of characters enclosed in quotes.
  • They are indexed and support slicing.
  • Strings are immutable.
  • You can concatenate strings using +.
  • String methods help modify and analyze text.
  • Escape characters allow special symbols.
  • Formatting allows variables inside strings.

? Syntax and Theory

A string literal can use either single or double quotes.

Strings behave like sequences and support indexing & slicing.

Strings are immutable, so operations return new strings.

? Code Examples

? Creating Simple Strings

? View Code Example
name = "Alice"
message = 'Hello, World!'

✂️ Slicing and Indexing Strings

? View Code Example
text = "Hello, World!"
print(text[0])     # H
print(text[2:5])   # llo
print(text[-1])    # !

? String Immutability

? View Code Example
name = "Alice"
# name[0] = "M"  # ❌ This will give an error

name = "Malice"  # Instead, assign a new value

⚙️ Using Common String Methods

? View Code Example
msg = "  Hello "
print(msg.strip())   # "Hello"
print(msg.lower())   # "  hello "
print(msg.upper())   # "  HELLO "

➕ String Concatenation

? View Code Example
first = "Python"
second = "Rocks"
result = first + " " + second
print(result)

? String Formatting

? View Code Example
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
print("My name is {} and I am {} years old.".format(name, age))

? Escape Characters

? View Code Example
print("She said, \"Hello!\"")
print("Line1\nLine2")
print("Backslash: \\\\")

? Common String Helper Functions

? View Code Example
txt = "Python is fun"
print(len(txt))         # string length
print(txt.find("is"))   # find index
print(txt.replace("fun", "awesome"))

? Live Output / Explanation

?️ What the Code Prints

  • Indexing prints selected characters.
  • strip() removes outer spaces.
  • len() returns number of characters.
  • find() returns where substring occurs.
  • replace() swaps text.

? Tips & Best Practices

  • Use f-strings for formatting.
  • Use strip() for cleaning input.
  • Use len() for validation.
  • Convert to lowercase before comparisons.

? Try It Yourself

  • Print the first and last characters of a string.
  • Ask user input and print in uppercase.
  • Use an f-string to print your name and city.
  • Reverse a string with slicing.