Python Strings Mastery
In Python, a string (str) is an immutable sequence of Unicode code points. Python 3 natively represents all text using UTF-8 encoding, allowing seamless support for international scripts, emojis, and scientific symbols.
Ways to Create Strings:
- Single Quotes (
'...'): Standard string literal. Useful when your text contains double quotation marks (e.g.'She said "Hello"'). - Double Quotes (
"..."): Functionally identical to single quotes. Useful when your text contains apostrophes (e.g."It's a sunny day"). - Triple Quotes (
"""..."""or'''...'''): Multi-line string literals that preserve literal newlines and indentation blocks. - Raw Strings (
r"..."): Prefixing a string withrdisables escape sequence processing (vital for regular expressions and Windows file paths liker"C:\Users\name").
Escape Characters: When you need to include special control characters inside a standard string, use a backslash (\):
| Escape Code | Meaning | Example |
|---|---|---|
\n | Newline (Line feed) | "Line 1\nLine 2" |
\t | Horizontal Tab space (4-8 spaces) | "Col 1\tCol 2" |
\' | Literal single quote | 'It\'s Python' |
\" | Literal double quote | "She said \"Hi\"" |
\\ | Literal backslash character | "path\\to\\file" |
# 1. Creating strings with single, double, and triple quotes
msg1 = 'Hello with single quotes'
msg2 = "Hello with double quotes (It's easy!)"
msg3 = """This is a
multi-line string
preserving newlines!"""
# 2. Escape characters demonstration
escaped_text = "Name:\tBalaji\nRole:\tPython Backend Engineer\nQuote:\t\"Keep Building!\""
print(msg1)
print(msg2)
print("\n--- Escape Characters Demo ---")
print(escaped_text)
\tinserts a clean tab spacing between column labels and values.\nforces the cursor to jump to a new line.\"embeds literal double quotation marks inside a double-quoted string without syntax error.
Because strings are ordered sequences, every character is assigned a numeric position (index). Python provides dual indexing:
Slicing Formula: string[start : stop : step]
start: Index where the slice begins (inclusive, defaults to 0).stop: Index where the slice ends (exclusive โ stops 1 character before!).step: Stride/increment between characters (defaults to 1; a negative step traverses backward!).
text = "Python Programming"
# 1. Indexing (Single Characters)
print("First character [0]:", text[0]) # P
print("Last character [-1]:", text[-1]) # g
# 2. Slicing sub-ranges
print("First 6 chars [0:6]:", text[0:6]) # Python
print("From index 7 to end [7:]:", text[7:]) # Programming
print("Every 2nd character [::2]:", text[::2]) # Pto rgamn
# 3. String Reversing with step=-1:
print("Reversed string [::-1]:", text[::-1])
Strings in Python are IMMUTABLE. Slicing never modifies the original string; it extracts and creates a brand new string object in memory.
Python strings come equipped with dozens of built-in methods for data sanitization, transformation, and case normalization:
len(s): Returns total character count (including whitespace).s.upper()/s.lower(): Converts all characters to uppercase or lowercase.s.title()/s.capitalize(): Capitalizes the first letter of each word or the sentence.s.strip(): Strips leading and trailing whitespace / newlines (use.lstrip()for left only,.rstrip()for right only).s.replace(old, new, count): Replaces occurrences of a substring with new text.
raw_input = " learn python programming today "
# 1. Length of string
print("Original Length:", len(raw_input))
# 2. Strip leading/trailing whitespace
cleaned = raw_input.strip()
print("Cleaned text:", repr(cleaned))
print("Cleaned Length:", len(cleaned))
# 3. Uppercase & Lowercase transformation
print("Uppercase:", cleaned.upper())
print("Title Case:", cleaned.title())
# 4. Replace substring
updated = cleaned.replace("python", "FastAPI & Python")
print("Replaced text:", updated)
Always apply .strip().lower() when validating user input (like email addresses or usernames) to avoid accidental whitespace or capitalization mismatch bugs.
Inspect and validate string content using search helpers:
s.find(sub): Returns index of first match (returns-1if not found).s.count(sub): Counts non-overlapping occurrences of substring.s.startswith(prefix): ReturnsTrueif string starts with prefix.s.endswith(suffix): ReturnsTrueif string ends with suffix.
filename = "data_report_2026.pdf"
# 1. Validating prefix and suffix
print("Is PDF file?", filename.endswith(".pdf")) # True
print("Is data file?", filename.startswith("data_")) # True
# 2. Searching substring position
pos = filename.find("report")
print("Position of 'report': index", pos) # index 5
# 3. Counting character occurrences
text_sample = "banana"
print("Count of letter 'a' in 'banana':", text_sample.count("a")) # 3
.find() returns -1 when a substring is missing, whereas .index() crashes with a ValueError. Use .find() for safer code.
Converting between strings and lists is one of the most common programming tasks:
s.split(delimiter): Breaks a string into a list of words or tokens based on a delimiter.delimiter.join(list): Combines a list of strings into a single string joined by the delimiter.- F-Strings (
f"..."): Clean expression interpolation introduced in Python 3.6.
# 1. Splitting CSV comma-separated data into a list
csv_line = "Apple,Banana,Mango,Orange"
fruits_list = csv_line.split(",")
print("Splitted List:", fruits_list)
# 2. Joining list items back with a custom separator
joined_str = " | ".join(fruits_list)
print("Joined String:", joined_str)
# 3. Modern f-string interpolation
user = "Balaji"
score = 98.75
message = f"Student {user} scored {score:.1f}% on the Python Exam!"
print("F-String Message:", message)
In Python, you write ", ".join(my_list) instead of my_list.join(", ") because join is a method of the string delimiter, allowing it to join any iterable (lists, tuples, sets, generators).
A palindrome is a word or phrase that reads the same forwards and backwards (e.g. "radar", "madam", "racecar").
In Python, string slicing makes checking palindromes remarkably clean and concise:
def is_palindrome(word):
# Step 1: Clean word (lowercase & strip whitespace)
cleaned = word.strip().lower()
# Step 2: Compare cleaned word with its reversed slice [::-1]
return cleaned == cleaned[::-1]
# Test palindrome cases:
test_words = ["Radar", "Python", "madam", "Racecar", "Compiler"]
for w in test_words:
result = "โ
Palindrome" if is_palindrome(w) else "โ Not Palindrome"
print(f"{w:10} -> {result}")
Radaris converted to lowercaseradar.- Reversed slice
radar[::-1]producesradar. radar == radarevaluates toTrue!
Writing word[0] = "H" raises TypeError: 'str' object does not support item assignment. Because strings are immutable, create a new string using slicing: word = "H" + word[1:].
Create a full name string, convert it to uppercase, count the vowels (a, e, i, o, u), and check if it is a palindrome.
text = "racecar"
print("Original:", text)
print("Uppercase:", text.upper())
print("Reversed:", text[::-1])
print("Is Palindrome:", text == text[::-1])
Q Why are strings in Python immutable?
Immutability allows strings to be hashable (usable as dictionary keys and set members), memory-efficient (via CPython string interning), and thread-safe in concurrent applications.
Q What is the difference between find() and index()?
find() returns -1 if the substring is not found, while index() raises a ValueError exception.
Q Can f-strings execute arbitrary Python expressions?
Yes! Inside {expr} in an f-string, you can call functions, perform math (f"{2+2}"), access dictionary keys, or format numbers (f"{price:,.2f}").