python-course-chapter-06
Chapter 6: Strings
Learn Python strings step by step with beginner explanations, examples, outputs, and clear output explanations.
Goal: Learn how to create, read, slice, change, search, validate, format, encode, and process text in Python.
6.1 What Is a String?
Beginner Explanation
A string is text stored inside quotation marks in Python. It can contain letters, numbers, spaces, punctuation, or symbols. Strings are used for names, messages, addresses, and other text values. Python reads everything inside matching quotation marks as one string value.
Python Example
name = "Maria"
print(name)
Explanation of the Output
The variable name stores the string "Maria". The print() function displays the text stored in that variable, so the output is Maria.
6.2 Creating Strings
Beginner Explanation
You create a string by writing text between single quotes, double quotes, or triple quotes. The opening and closing quotation marks must match. After creating a string, you can store it in a variable, display it, combine it, or use string methods.
Python Example
city = "Toronto"
message = 'Welcome'
print(city)
print(message)
Explanation of the Output
Python creates two separate strings. The variable city stores Toronto, and message stores Welcome. Each print() call displays one value on its own line.
6.3 Single Quotes
Beginner Explanation
Single quotes can be used to create short or long strings. They are useful when the text contains double quotation marks. The string must begin and end with a single quote. An apostrophe inside the text needs special handling because Python may think it ends the string.
Python Example
text = 'Python is easy'
print(text)
Explanation of the Output
The words are placed between single quotation marks, so Python treats them as text. The quotation marks are not displayed because they only mark the beginning and end of the string.
6.4 Double Quotes
Beginner Explanation
Double quotes also create strings in Python. They are especially helpful when the text contains an apostrophe, such as a person’s name or a contraction. The opening and closing double quotes must match. Single-quoted and double-quoted strings behave the same way.
Python Example
message = "It's a sunny day"
print(message)
Explanation of the Output
The apostrophe in It's does not end the string because the string uses double quotation marks. Python displays the complete sentence without displaying the surrounding quotes.
6.5 Triple Quotes
Beginner Explanation
Triple quotes use three single quotes or three double quotes. They can hold text that continues across several lines. Triple quotes are also used for docstrings. They are useful when a message is too long for one line or when you want to preserve line breaks.
Python Example
text = """Python
Strings
Tutorial"""
print(text)
Output
Python
Strings
Tutorial
Explanation of the Output
The triple-quoted string contains three lines. Python preserves the line breaks exactly as written, so each word appears on a separate output line.
6.6 Multiline Strings
Beginner Explanation
A multiline string contains text on more than one line. Triple quotation marks make multiline strings easy to write. Line breaks inside the string become part of the value. Multiline strings are useful for letters, menus, poems, instructions, and long messages.
Python Example
menu = """1. Start
2. Settings
3. Exit"""
print(menu)
Output
1. Start
2. Settings
3. Exit
Explanation of the Output
The string includes three lines. When print() displays the value, Python keeps every line break, so the menu appears in the same vertical arrangement.
6.7 String Indexing
Beginner Explanation
String indexing means selecting one character from a string by its position. Every character has an index number. Python starts counting from zero, not one. You place the index inside square brackets after the string or variable name.
Python Example
word = "Python"
print(word[0])
print(word[3])
Explanation of the Output
Index 0 selects the first character, which is P. Index 3 selects the fourth character, which is h, because counting begins at zero.
6.8 Positive Indexing
Beginner Explanation
Positive indexing counts characters from left to right. The first character has index zero, the second has index one, and so on. Positive indexes are useful when you know a character’s position from the beginning of a string.
Python Example
text = "Computer"
print(text[0])
print(text[1])
print(text[7])
Explanation of the Output
The indexes select characters from left to right. Index 0 is C, index 1 is o, and index 7 is the final character r.
6.9 Negative Indexing
Beginner Explanation
Negative indexing counts characters from right to left. The last character has index minus one, the second-last has index minus two, and so on. It is useful when you need characters near the end without calculating the string’s full length.
Python Example
word = "Python"
print(word[-1])
print(word[-2])
Explanation of the Output
Index -1 selects the final character, n. Index -2 moves one position left and selects o.
6.10 String Slicing
Beginner Explanation
String slicing extracts a section of a string. A slice uses a starting index and a stopping index separated by a colon. Python includes the starting position but does not include the stopping position. The original string is not changed.
Python Example
word = "Programming"
print(word[0:7])
print(word[7:11])
Explanation of the Output
The first slice begins at index 0 and stops before index 7, producing Program. The second slice starts at index 7 and continues before index 11, producing ming.
6.11 Slice Start, Stop, and Step
Beginner Explanation
A complete slice can contain a start, stop, and step value. The start says where to begin, the stop says where to end, and the step says how many positions to move each time. A step of two selects every second character.
Python Example
text = "0123456789"
print(text[1:8:2])
Explanation of the Output
Python begins at index 1, stops before index 8, and moves two positions each time. It therefore selects 1, 3, 5, and 7.
6.12 Reversing Strings
Beginner Explanation
A common way to reverse a string is to use slicing with a step of minus one. The negative step tells Python to move backward through the string. This is useful for checking palindromes or displaying text in reverse order.
Python Example
word = "Python"
reversed_word = word[::-1]
print(reversed_word)
Explanation of the Output
The slice has no start or stop value, so it uses the whole string. The step -1 reads the characters from the end to the beginning, producing nohtyP.
6.13 String Immutability
Beginner Explanation
Strings are immutable, which means their individual characters cannot be changed after the string is created. To make a change, you create a new string. This helps Python manage strings safely and predictably.
Python Example
word = "cat"
new_word = "b" + word[1:]
print(new_word)
Explanation of the Output
The original string cat is not changed directly. Python combines b with the slice at and stores the new string bat in another variable.
6.14 String Length
Beginner Explanation
The built-in len() function returns the number of characters in a string. Spaces and punctuation marks are also counted. String length is useful when checking passwords, validating user input, or finding the last index.
Python Example
text = "Hello World"
print(len(text))
Explanation of the Output
The string has five letters in Hello, one space, and five letters in World. That makes a total length of 11.
6.15 Looping Through Strings
Beginner Explanation
A for loop can visit every character in a string one at a time. During each loop cycle, the next character is placed in a variable. This is useful for counting letters, checking symbols, or processing text character by character.
Python Example
word = "Cat"
for letter in word:
print(letter)
Explanation of the Output
The loop runs three times because the string has three characters. Each cycle stores one character in letter and prints it on a separate line.
6.16 Checking String Membership
Beginner Explanation
The in operator checks whether text appears inside another string. It returns True when the text is found and False when it is not found. The not in operator checks the opposite condition.
Python Example
sentence = "I am learning Python"
print("Python" in sentence)
print("Java" in sentence)
Explanation of the Output
Python appears in the sentence, so the first check returns True. Java does not appear, so the second check returns False.
6.17 String Concatenation
Beginner Explanation
String concatenation means joining strings together. Python uses the plus operator to combine text values. You may need to add a space between words because Python does not insert one automatically when using plus.
Python Example
first = "Hello"
second = "World"
message = first + " " + second
print(message)
Explanation of the Output
Python joins Hello, a space, and World. The combined result is stored in message and then displayed.
6.18 String Repetition
Beginner Explanation
The multiplication operator repeats a string a chosen number of times. The string is written on one side and an integer on the other. This is useful for separators, patterns, repeated symbols, or simple text designs.
Python Example
line = "-" * 8
print(line)
Explanation of the Output
Python repeats the hyphen string eight times. The repeated characters are joined into one new string containing eight hyphens.
6.19 Escape Characters
Beginner Explanation
Escape characters begin with a backslash and represent special characters inside a string. For example, backslash-n creates a new line, backslash-t creates a tab, and a backslash can allow quotation marks inside matching quotes.
Python Example
print("Name:\tAli\nCity:\tToronto")
Output
Name: Ali
City: Toronto
Explanation of the Output
The \t escape adds horizontal spacing, while \n moves the following text to a new line. Python interprets these combinations instead of printing them literally.
6.20 Raw Strings
Beginner Explanation
A raw string begins with the letter r before the opening quote. In a raw string, backslashes are usually treated as ordinary characters instead of escape characters. Raw strings are helpful for Windows paths and regular expressions.
Python Example
path = r"C:\Users\Majid\Documents"
print(path)
Output
C:\Users\Majid\Documents
Explanation of the Output
Because the string begins with r, Python keeps each backslash as a visible character. It does not treat combinations such as \U as escape sequences.
6.21 Unicode Strings
Beginner Explanation
Python strings support Unicode, which allows text from many languages and includes symbols and emoji. You can store English, Persian, French, Chinese, Arabic, and many other characters in ordinary strings.
Python Example
message = "Hello سلام 🌍"
print(message)
Explanation of the Output
Python stores and displays the English text, Persian text, and globe emoji in the same string because normal Python strings support Unicode characters.
6.22 String Methods
Beginner Explanation
String methods are built-in actions that work with string values. A method is written after a string or variable using a dot. Methods can change case, remove spaces, replace text, split text, search, and perform many other operations.
Python Example
word = "python"
print(word.upper())
Explanation of the Output
The upper() method creates a new uppercase version of the string. The original variable still contains python unless the new result is assigned back to it.
6.23 Changing String Case
Beginner Explanation
Python provides methods for changing letter case. upper() creates uppercase text, lower() creates lowercase text, title() capitalizes words, and capitalize() changes the first character to uppercase.
Python Example
text = "python programming"
print(text.upper())
print(text.title())
Output
PYTHON PROGRAMMING
Python Programming
Explanation of the Output
The first method changes every letter to uppercase. The second method capitalizes the first letter of each word while leaving the remaining letters lowercase.
6.24 Removing Whitespace
Beginner Explanation
Whitespace includes spaces, tabs, and line breaks. The strip() method removes whitespace from both ends of a string. lstrip() removes it from the left, and rstrip() removes it from the right.
Python Example
name = " Alice "
print(name.strip())
Explanation of the Output
The original string has extra spaces before and after the name. strip() removes spaces from both ends, so only Alice is displayed.
6.25 Replacing Text
Beginner Explanation
The replace() method creates a new string in which selected text is replaced with different text. It does not modify the original string. You provide the old text first and the new text second.
Python Example
sentence = "I like cats"
new_sentence = sentence.replace("cats", "dogs")
print(new_sentence)
Explanation of the Output
Python finds the substring cats and replaces it with dogs. The new sentence is stored in new_sentence and displayed.
6.26 Splitting Strings
Beginner Explanation
The split() method divides a string into smaller strings and returns them in a list. By default, it splits at spaces. You can also provide a comma, hyphen, or another separator.
Python Example
text = "red,green,blue"
colors = text.split(",")
print(colors)
Output
['red', 'green', 'blue']
Explanation of the Output
Python uses each comma as a dividing point. It creates a list containing three separate string values: red, green, and blue.
6.27 Joining Strings
Beginner Explanation
The join() method combines several strings into one string. The string before join() becomes the separator placed between the items. This is useful for turning a list of words into a sentence or formatted line.
Python Example
words = ["Python", "is", "fun"]
sentence = " ".join(words)
print(sentence)
Explanation of the Output
The space string before join() is inserted between each list item. Python combines the three words into one sentence.
6.28 Searching Strings
Beginner Explanation
The find() method searches for text and returns the index where it first appears. If the text is not found, it returns minus one. The index() method is similar, but it raises an error when the text is missing.
Python Example
text = "Learn Python today"
print(text.find("Python"))
print(text.find("Java"))
Explanation of the Output
Python begins at index 6, so the first call returns 6. Java is not found, so the second call returns -1.
6.29 Counting Substrings
Beginner Explanation
The count() method tells you how many times a character or substring appears in a string. It is case-sensitive, so uppercase and lowercase forms are counted separately. This is useful for simple text analysis.
Python Example
text = "banana"
print(text.count("a"))
print(text.count("na"))
Explanation of the Output
The letter a appears three times in banana. The substring na appears two times, so the method returns 2.
6.30 String Validation Methods
Beginner Explanation
Validation methods check what kind of characters a string contains. isalpha() checks for letters, isdigit() checks for digits, isalnum() checks for letters and numbers, and isspace() checks for whitespace.
Python Example
print("Python".isalpha())
print("12345".isdigit())
print("abc123".isalnum())
Explanation of the Output
Each string matches the method being used. Python contains only letters, 12345 contains only digits, and abc123 contains only letters and digits.
6.31 String Alignment
Beginner Explanation
Alignment methods add spacing so text fits a chosen width. ljust() aligns text to the left, rjust() aligns it to the right, and center() places it in the middle. These methods are useful for reports and menus.
Python Example
word = "Python"
print(word.center(12, "-"))
Explanation of the Output
The final string must have a width of twelve characters. Python places the six-letter word in the middle and adds three hyphens on each side.
6.32 String Formatting
Beginner Explanation
String formatting places values inside a prepared piece of text. It helps combine words, numbers, and variables cleanly. Python supports several formatting styles, including format(), f-strings, and older percent formatting.
Python Example
name = "Sara"
age = 20
message = f"{name} is {age} years old."
print(message)
Output
Sara is 20 years old.
Explanation of the Output
The placeholders inside the f-string are replaced by the values stored in name and age. Python then displays the completed sentence.
6.33 The format() Method
Beginner Explanation
The format() method replaces curly-brace placeholders with supplied values. Values are placed into the braces in order unless indexes or names are used. It is useful in older code and remains fully supported.
Python Example
product = "Book"
price = 15
print("{} costs ${}.".format(product, price))
Explanation of the Output
The first pair of braces receives Book, and the second receives 15. The completed string is then printed.
6.34 F-Strings
Beginner Explanation
F-strings are a modern and readable way to insert variables and expressions into strings. Place the letter f before the opening quote and put variables or expressions inside curly braces. Python evaluates each placeholder automatically.
Python Example
item = "Notebook"
price = 4.5
print(f"The {item} costs ${price}.")
Output
The Notebook costs $4.5.
Explanation of the Output
Python replaces {item} with Notebook and {price} with 4.5. The rest of the sentence remains unchanged.
6.35 Format Specifiers
Beginner Explanation
Format specifiers control how values appear inside formatted strings. They can set decimal places, percentages, widths, alignment, or number separators. A colon inside a placeholder introduces the formatting instruction.
Python Example
price = 12.5
print(f"Price: ${price:.2f}")
Explanation of the Output
The format specifier .2f tells Python to display the floating-point number with exactly two digits after the decimal point.
6.36 String Encoding and Decoding
Beginner Explanation
Encoding converts a string into bytes so it can be stored or transmitted. Decoding converts bytes back into a normal string. UTF-8 is a common encoding that supports many languages and symbols.
Python Example
text = "Hello"
data = text.encode("utf-8")
print(data)
print(data.decode("utf-8"))
Explanation of the Output
The first output is a bytes value, shown by the leading b. The second line decodes those bytes back into the original string Hello.
6.37 Regular Strings vs Bytes
Beginner Explanation
A regular string stores human-readable Unicode text. A bytes object stores raw byte values used for files, networks, images, and encoded data. Although they may look similar, strings and bytes are different Python types.
Python Example
text = "ABC"
data = b"ABC"
print(type(text))
print(type(data))
Output
<class 'str'>
<class 'bytes'>
Explanation of the Output
The first value is a normal string, so its type is str. The second begins with b, so Python identifies it as a bytes object.
6.38 Practical String Processing
Beginner Explanation
Practical string processing combines several string operations to clean and prepare user data. A program may remove spaces, correct letter case, replace characters, or split information. These steps are common in forms and data-entry applications.
Python Example
raw_name = " aLiCe smith "
clean_name = raw_name.strip().title()
print(clean_name)
Explanation of the Output
First, strip() removes spaces from both ends. Then title() capitalizes the first letter of each word, producing Alice Smith.
6.39 Chapter Practice Exercises
Beginner Explanation
Practice exercises help you remember how strings work. Try creating strings, selecting characters, slicing text, using methods, checking membership, and formatting values. Write each exercise yourself before looking at an answer so that you build confidence.
Python Example
name = "Michael"
print(name[0])
print(name[-1])
print(name.upper())
Explanation of the Output
The first expression selects the first letter. The second uses negative indexing to select the last letter. The final method creates an uppercase version of the complete name.
6.40 Chapter Mini Project
Beginner Explanation
This mini project creates a simple name formatter. It asks the user for a first and last name, removes unwanted spaces, corrects capitalization, combines the names, and displays a welcome message. It uses input, strip, title, concatenation, and formatting.
Python Example
first = input("Enter your first name: ").strip().title()
last = input("Enter your last name: ").strip().title()
full_name = first + " " + last
print(f"Welcome, {full_name}!")
Output
Enter your first name: majid
Enter your last name: farjani
Welcome, Majid Farjani!
Explanation of the Output
The program collects two text values. strip() removes extra spaces, and title() corrects capitalization. The names are joined with a space, and the f-string displays the final welcome message.