LEARN COMPLETE PYTHON IN 24 HOURS
9. Strings (Deep Dive)
Strings are sequences of characters (text). They are immutable (cannot be changed after creation, like tuples).
9.1 String Slicing & Negative Indexing
Strings support indexing and slicing — just like lists.
Indexing:
Positive: starts from 0 (left to right)
Negative: starts from -1 (right to left)
Example:
Python
text = "Python Programming" print(text[0]) # P print(text[6]) # P (space is also a character) print(text[-1]) # g print(text[-9]) # r
Slicing Syntax:
Python
text[start:end:step] # start → inclusive # end → exclusive # step → optional (default 1)
Examples:
Python
print(text[0:6]) # Python print(text[7:]) # Programming print(text[:6]) # Python print(text[::2]) # Pto rgamn (every 2nd character) print(text[::-1]) # gnimmargorP nohtyP (reversed string!) print(text[-12:-6]) # Progra (negative slicing) print(text[7:18:3]) # Porm (start 7, step 3)
Tip: Slicing creates a new string — original remains unchanged. Common use: Reverse a string → text[::-1]
9.2 String Methods (upper, lower, strip, replace, split, join, find, etc.)
Strings have many useful built-in methods.
MethodDescriptionExampleResultupper()Convert to uppercase"hello".upper()"HELLO"lower()Convert to lowercase"HELLO".lower()"hello"title()Capitalize first letter of each word"python is fun".title()"Python Is Fun"capitalize()Capitalize first letter only"python is fun".capitalize()"Python is fun"strip()Remove leading/trailing whitespace" hello ".strip()"hello"lstrip() / rstrip()Remove left/right whitespace only" hello ".lstrip()"hello "replace(old, new)Replace substring"I like Java".replace("Java", "Python")"I like Python"split()Split string into list (default: space)"apple banana mango".split()['apple', 'banana', 'mango']split(sep)Split by specific separator"name,age,city".split(",")['name', 'age', 'city']join()Join list elements with separator"-".join(["2026", "03", "05"])"2026-03-05"find(sub)Return first index of substring (or -1)"hello world".find("world")6index(sub)Like find(), but raises error if not found"hello".index("l")2startswith() / endswith()Check prefix/suffix"python.py".endswith(".py")Truecount(sub)Count occurrences"banana".count("a")3
Practical Examples:
Python
sentence = " Python is awesome! Learn Python today. " print(sentence.strip()) # "Python is awesome! Learn Python today." print(sentence.upper()) # " PYTHON IS AWESOME! LEARN PYTHON TODAY. " print(sentence.replace("Python", "Java")) # " Java is awesome! Learn Java today. " words = sentence.split() # ['Python', 'is', 'awesome!', 'Learn', 'Python', 'today.'] print(words) date_parts = ["2026", "March", "05"] print("/".join(date_parts)) # 2026/March/05 print(sentence.find("awesome")) # 10 (first occurrence) print(sentence.count("Python")) # 2
Tip: join() is the opposite of split() — very useful for creating CSV, paths, etc.
9.3 Check if String Contains Something
Several ways to check:
in operator (most common & readable)
Python
text = "I love Python programming" print("Python" in text) # True print("java" in text) # False print("python" in text.lower()) # True (case-insensitive)
find() or index()
Python
if text.find("love") != -1: print("Found 'love' at position:", text.find("love")) # 2
startswith() / endswith()
Python
filename = "report.pdf" print(filename.endswith(".pdf")) # True print(filename.startswith("report")) # True
Tip: For case-insensitive check → convert both to lower/upper first.
9.4 Escape Characters
Use \ (backslash) to include special characters inside strings.
Escape SequenceMeaningExampleOutput\nNew line"Line1\nLine2"Line1 Line2\tTab"Name:\tAnshuman"Name: Anshuman\\Backslash"Path\to\file"Path\to\file\"Double quote inside """He said "Hello""He said "Hello"\'Single quote inside '''It's Python'It's Python
Example:
Python
print("Hello\nWorld!") # Hello # World! print("C:\\Users\\Anshuman") # C:\Users\Anshuman print("She said, \"I love Python!\"") # She said, "I love Python!"
Tip: Use raw strings to ignore escapes → add r before quotes:
Python
print(r"C:\new\test") # C:\new\test (no new line)
9.5 Multiline Strings
Create strings that span multiple lines.
Two ways:
Triple quotes """ """ or ''' '''
Python
message = """ Hello Anshuman, Welcome to Python tutorial 2026! This is a multiline string. Enjoy learning! """ print(message)
Output:
text
Hello Anshuman, Welcome to Python tutorial 2026! This is a multiline string. Enjoy learning!
Using \ at end of each line (inside single/double quotes)
Python
long_text = "Python is great because " \ "it is easy to read " \ "and write." print(long_text)
Tip: Triple quotes preserve newlines and indentation — very useful for:
Docstrings (function/class documentation)
HTML templates
SQL queries
Long messages/emails
Mini Project – Text Cleaner & Analyzer
Python
text = input("Enter some text: ").strip() # Clean and analyze clean_text = text.lower().replace(",", "").replace(".", "") words = clean_text.split() print("Original:", text) print("Lowercase:", text.lower()) print("Word count:", len(words)) print("Contains 'python'?", "python" in clean_text) print("First word:", words[0] if words else "Empty")
This completes the full Strings (Deep Dive) section — now you can handle text like a pro!
Dictionaries. Dictionaries are one of Python's most powerful and commonly used data structures — perfect for storing data in key-value pairs (like a real dictionary: word → meaning).
Written in simple English with syntax, many practical examples, outputs, and tips — ready to copy-paste directly into your webpage.
Email-ibm.anshuman@gmail.com
© 2026 CodeForge AI | Privacy Policy |Terms of Service | Contact | Disclaimer | 1000 university college list|book library australia 2026
All my books are exclusively available on Amazon. The free notes/materials on globalcodemaster.com do NOT match even 1% with any of my PUBLISHED BOoks. Similar topics ≠ same content. Books have full details, exercises, chapters & structure — website notes do not.No book content is shared here. We fully comply with Amazon policies.