String Basics
String Basics
Section titled “String Basics”Introduction
Section titled “Introduction”A string is an immutable sequence of Unicode characters. In Python 3, all strings are Unicode by default.
Creating Strings
Section titled “Creating Strings”s1 = 'Hello' # Single quotess2 = "World" # Double quotess3 = '''Triple single''' # Multi-lines4 = """Triple double""" # Multi-line
# String repetitionprint("Ha" * 3) # HaHaHaprint(len("Hello")) # 5Indexing
Section titled “Indexing”s = "Python"
# Positive indexingprint(s[0]) # Pprint(s[5]) # n
# Negative indexingprint(s[-1]) # n (last character)print(s[-6]) # PSlicing
Section titled “Slicing”s = "Hello, World!"
print(s[0:5]) # Helloprint(s[7:12]) # Worldprint(s[:5]) # Hello (start defaults to 0)print(s[7:]) # World! (stop defaults to end)print(s[::2]) # Hlo ol! (every 2nd character)print(s[::-1]) # Reverse!Immutability
Section titled “Immutability”s = "Hello"# s[0] = "J" # TypeError! Strings can't be modified
# Create new string insteads = "J" + s[1:] # "Jello"String Methods
Section titled “String Methods”s = " Hello, World! "
# Case methodsprint(s.upper()) # " HELLO, WORLD! "print(s.lower()) # " hello, world! "print(s.title()) # " Hello, World! "print(s.strip()) # "Hello, World!"
# Findingprint(s.find("World")) # 7print(s.find("xyz")) # -1 (not found)print(s.count("l")) # 3
# Replacingprint(s.replace("World", "Python")) # "Hello, Python!"
# Splitting and Joiningwords = s.split(",") # [' Hello', ' World! ']print("-".join(["a", "b", "c"])) # a-b-c
# Checkingprint("hello123".isalnum()) # Trueprint("hello".isalpha()) # Trueprint("123".isdigit()) # TrueWhy It Matters
Section titled “Why It Matters”Strings are the most common data type in programming — used for text processing, user interaction, data parsing, and more.
Interview Questions
Section titled “Interview Questions”Q1: What is string immutability and why does it matter?
A: Strings cannot be modified after creation. This makes them hashable (dict keys), thread-safe, and allows Python to intern them for efficiency.
Q2: What’s the difference between find() and index()?
A: find() returns -1 if not found; index() raises ValueError.
Practice Exercises
Section titled “Practice Exercises”- Reverse a string without using
[::-1]. - Check if a string is a palindrome.
- Count character frequency in a string.