Docs

README

02 - Strings

📌 What You'll Learn

  • String creation and basics
  • String indexing and slicing
  • String methods
  • String formatting
  • Escape characters
  • Raw strings
  • Introduction to regular expressions

🔤 String Basics

Strings are sequences of characters enclosed in quotes. Python treats single quotes '...' and double quotes "..." the same.

# Creating strings
single = 'Hello'
double = "World"
multi_line = """This is
a multi-line
string"""

# Empty string
empty = ""

# String with quotes inside
quote1 = "He said 'Hello'"
quote2 = 'She said "Hi"'

String Properties

  • Immutable: Cannot change individual characters
  • Ordered: Characters have a specific position (index)
  • Iterable: Can loop through each character

📍 String Indexing

Access individual characters using their index (position).

String:   P  y  t  h  o  n
Index:    0  1  2  3  4  5
Negative: -6 -5 -4 -3 -2 -1
text = "Python"

# Positive indexing (starts from 0)
print(text[0])   # P (first character)
print(text[1])   # y
print(text[5])   # n (last character)

# Negative indexing (starts from -1)
print(text[-1])  # n (last character)
print(text[-2])  # o (second to last)
print(text[-6])  # P (first character)

✂️ String Slicing

Extract a portion of a string using [start:end:step].

text = "Python Programming"

# Basic slicing [start:end] - end is NOT included
print(text[0:6])    # Python
print(text[7:18])   # Programming

# Omitting start or end
print(text[:6])     # Python (from beginning)
print(text[7:])     # Programming (to end)
print(text[:])      # Python Programming (copy)

# With step
print(text[::2])    # Pto rgamn (every 2nd char)
print(text[::3])    # Ph oam

# Negative slicing
print(text[-11:])   # Programming
print(text[:-12])   # Python

# Reverse a string
print(text[::-1])   # gnimmargorP nohtyP

🛠️ String Methods

Python provides many built-in methods for string manipulation.

Case Methods

text = "Hello World"

print(text.upper())       # HELLO WORLD
print(text.lower())       # hello world
print(text.title())       # Hello World
print(text.capitalize())  # Hello world
print(text.swapcase())    # hELLO wORLD
print(text.casefold())    # hello world (aggressive lowercase)

Search Methods

text = "Hello World, Hello Python"

# Find - returns index (-1 if not found)
print(text.find("World"))     # 6
print(text.find("Java"))      # -1
print(text.rfind("Hello"))    # 13 (rightmost)

# Index - like find but raises error if not found
print(text.index("World"))    # 6
# print(text.index("Java"))   # ValueError!

# Count occurrences
print(text.count("Hello"))    # 2
print(text.count("l"))        # 5

# Check presence
print("World" in text)        # True
print("Java" in text)         # False

Check Methods (return boolean)

# All these return True or False
print("Hello".isalpha())      # True (only letters)
print("12345".isdigit())      # True (only digits)
print("Hello123".isalnum())   # True (letters or digits)
print("   ".isspace())        # True (only whitespace)
print("Hello".islower())      # False
print("HELLO".isupper())      # True
print("Hello World".istitle())# True (title case)
print("hello".startswith("he"))# True
print("hello".endswith("lo")) # True

Modification Methods

text = "  Hello World  "

# Strip whitespace
print(text.strip())        # "Hello World"
print(text.lstrip())       # "Hello World  "
print(text.rstrip())       # "  Hello World"

# Replace
print(text.strip().replace("World", "Python"))  # "Hello Python"
print("aaa".replace("a", "b", 2))  # "bba" (limit replacements)

# Split and Join
sentence = "apple,banana,cherry"
fruits = sentence.split(",")      # ['apple', 'banana', 'cherry']
print("-".join(fruits))           # "apple-banana-cherry"

# Split with limit
print("a-b-c-d".split("-", 2))    # ['a', 'b', 'c-d']

# Split lines
multi = "Line1\nLine2\nLine3"
print(multi.splitlines())         # ['Line1', 'Line2', 'Line3']

Alignment Methods

text = "Python"

# Center, left, right align
print(text.center(20))       # "       Python       "
print(text.center(20, "-"))  # "-------Python-------"
print(text.ljust(20, "."))   # "Python.............."
print(text.rjust(20, "."))   # "..............Python"
print(text.zfill(10))        # "0000Python" (zero fill)

# For numbers
num = "42"
print(num.zfill(5))          # "00042"

📝 String Formatting

1. f-strings (Python 3.6+) - Recommended!

name = "Alice"
age = 25
height = 1.756

# Basic
print(f"Name: {name}, Age: {age}")

# Expressions inside braces
print(f"Next year: {age + 1}")
print(f"Name uppercase: {name.upper()}")

# Format specifiers
print(f"Height: {height:.2f}")     # 2 decimal places: 1.76
print(f"Age: {age:05d}")           # Zero-padded: 00025
print(f"Name: {name:>10}")         # Right-align: "     Alice"
print(f"Name: {name:<10}")         # Left-align: "Alice     "
print(f"Name: {name:^10}")         # Center: "  Alice   "

# Number formatting
big_num = 1000000
print(f"Number: {big_num:,}")      # 1,000,000
print(f"Number: {big_num:_}")      # 1_000_000

# Percentage
ratio = 0.756
print(f"Percentage: {ratio:.1%}")  # 75.6%

# Binary, hex, octal
num = 255
print(f"Binary: {num:b}")          # 11111111
print(f"Hex: {num:x}")             # ff
print(f"Octal: {num:o}")           # 377

2. format() Method

# Positional arguments
print("{} is {} years old".format("Alice", 25))

# Numbered arguments
print("{0} is {1}, {0} likes Python".format("Bob", 30))

# Named arguments
print("{name} is {age}".format(name="Charlie", age=35))

# Format specifiers
print("{:.2f}".format(3.14159))    # 3.14
print("{:>10}".format("Hi"))       # "        Hi"

3. % Operator (Old style)

name = "David"
age = 40

print("Name: %s, Age: %d" % (name, age))
print("Pi: %.2f" % 3.14159)

🔀 Escape Characters

Special characters that start with backslash \.

# Common escape characters
print("Hello\nWorld")    # Newline
print("Hello\tWorld")    # Tab
print("She said \"Hi\"") # Double quote
print('It\'s Python')    # Single quote
print("Back\\slash")     # Backslash
print("Hello\rWorld")    # Carriage return

# All escape characters:
# \n  - Newline
# \t  - Tab
# \\  - Backslash
# \'  - Single quote
# \"  - Double quote
# \r  - Carriage return
# \b  - Backspace
# \f  - Form feed
# \ooo - Octal value
# \xhh - Hex value

📜 Raw Strings

Prefix with r to treat backslashes as literal characters.

# Normal string - \n creates newline
print("C:\new_folder")   # C:
                         # ew_folder

# Raw string - backslash is literal
print(r"C:\new_folder")  # C:\new_folder

# Useful for:
# - Windows file paths
# - Regular expressions
path = r"C:\Users\name\Documents"
pattern = r"\d+\.\d+"

🔗 String Concatenation and Repetition

# Concatenation
first = "Hello"
last = "World"
full = first + " " + last  # "Hello World"

# Repetition
line = "-" * 20           # "--------------------"
pattern = "ab" * 3        # "ababab"

# Join (more efficient for many strings)
words = ["Hello", "World", "Python"]
sentence = " ".join(words)  # "Hello World Python"

🔍 Regular Expressions (Introduction)

The re module provides pattern matching capabilities.

import re

text = "My email is john@example.com and phone is 123-456-7890"

# Search for pattern
match = re.search(r'\d{3}-\d{3}-\d{4}', text)
if match:
    print(match.group())  # 123-456-7890

# Find all matches
emails = re.findall(r'\S+@\S+', text)
print(emails)  # ['john@example.com']

# Replace pattern
new_text = re.sub(r'\d', 'X', text)
print(new_text)  # My email is john@example.com and phone is XXX-XXX-XXXX

# Common patterns:
# \d - digit
# \w - word character (letter, digit, underscore)
# \s - whitespace
# .  - any character
# *  - 0 or more
# +  - 1 or more
# ?  - 0 or 1
# {n} - exactly n times

🔧 Useful String Operations

# Length
print(len("Python"))      # 6

# Character to ASCII
print(ord('A'))           # 65

# ASCII to character
print(chr(65))            # 'A'

# Check empty string
text = ""
if not text:
    print("String is empty")

# Remove prefix/suffix (Python 3.9+)
print("HelloWorld".removeprefix("Hello"))  # "World"
print("HelloWorld".removesuffix("World"))  # "Hello"

# Partition
print("Hello=World".partition("="))  # ('Hello', '=', 'World')

📝 Summary

OperationSyntaxExample
Indexingstr[i]"Python"[0]"P"
Slicingstr[start:end:step]"Python"[0:3]"Pyt"
Lengthlen(str)len("Hi")2
Concatenatestr1 + str2"a" + "b""ab"
Repeatstr * n"a" * 3"aaa"
Upperstr.upper()"hi".upper()"HI"
Lowerstr.lower()"HI".lower()"hi"
Stripstr.strip()" hi ".strip()"hi"
Splitstr.split(sep)"a,b".split(",")["a","b"]
Joinsep.join(list)",".join(["a","b"])"a,b"
Replacestr.replace(old,new)"ab".replace("a","x")"xb"
Findstr.find(sub)"abc".find("b")1
Formatf"{var}"f"Hi {name}"

🎯 Next Steps

After mastering strings, proceed to 03_control_flow to learn about conditions and loops!

README - Python Tutorial | DeepML