Module 4: Strings in Python
Strings are one of the most important and frequently used data types in Python. Whenever a program works with text—such as names, email addresses, messages, usernames, URLs, file paths, or website content—you are working with strings.
Python provides powerful tools for creating, accessing, searching, modifying, formatting, and validating text.
By the end of this module, you will be able to:
- Create strings using different quotation styles
- Access individual characters using indexing
- Use positive and negative indexing
- Extract portions of text using slicing
- Use important built-in string methods
- Format strings using f-strings
- Work with escape characters and raw strings
- Create multiline strings
- Validate and process user input
- Build practical string-processing programs
- Understand string immutability and common errors
What Is a String?
A string is a sequence of characters enclosed inside quotation marks.
Python supports three common quotation styles:
1'Single quotes' 2"Double quotes" 3"""Triple quotes"""
Single and double quotes are commonly used for normal strings, while triple quotes are useful for multiline text.
Basic Example
1name = "Ankit" 2city = "Delhi" 3 4print(name) 5print(city)
Output:
1Ankit 2Delhi
You can use either single or double quotes:
1language = "Python" 2framework = 'Django' 3 4print(language) 5print(framework)
The important rule is that the opening and closing quotation marks must match.
Why Are Strings Important?
Strings are used in almost every real-world application.
For example:
- Usernames
- Passwords
- Email addresses
- Messages
- File names
- URLs
- Product names
- Search queries
- Website content
- Chat messages
- Database records
- Log messages
Consider a simple registration program:
1username = input("Enter username: ") 2email = input("Enter email: ") 3 4print(f"Account created for {username}") 5print(f"Confirmation sent to {email}")
Here, both username and email contain string values.
1. Creating Strings
The simplest way to create a string is to assign text to a variable.
1language = "Python" 2 3print(language)
Output:
1Python
Single Quotes
1language = 'Python' 2 3print(language)
Double Quotes
1language = "Python" 2 3print(language)
Both examples create a value of type str.
Triple Quotes
Triple quotes are useful when a string contains multiple lines.
1message = """Welcome to Python. 2This is a multiline string. 3Keep learning and practicing!""" 4 5print(message)
Output:
1Welcome to Python. 2This is a multiline string. 3Keep learning and practicing!
Triple quotes can also be written using three single quotes:
1message = '''Line one 2Line two 3Line three''' 4 5print(message)
Checking the Type of a String
Python provides the type() function to determine the type of a value.
1language = "Python" 2 3print(type(language))
Output:
1<class 'str'>
str is Python's built-in type for strings.
Finding the Length of a String
Use the len() function to find the number of characters in a string.
1language = "Programming" 2 3print(len(language))
Output:
111
Spaces are also counted as characters.
1text = "Hello World" 2 3print(len(text))
Output:
111
There are 10 letters plus 1 space.
2. String Indexing
A string is a sequence of characters, and every character has a position called an index.
Python uses zero-based indexing, which means the first character is at index 0.
For the string "Python":
1Character: P y t h o n 2Index: 0 1 2 3 4 5
Accessing Individual Characters
1word = "Python" 2 3print(word[0]) 4print(word[1]) 5print(word[2]) 6print(word[5])
Output:
1P 2y 3t 4n
Accessing a Character from Another String
1name = "Ankit" 2 3print(name[0]) 4print(name[2]) 5print(name[4])
Output:
1A 2k 3t
Remember:
The first character always starts at index
0.
Handling an Invalid Index
Trying to access an index that does not exist raises an IndexError.
1word = "Python" 2 3print(word[10])
Output:
1IndexError: string index out of range
The string "Python" contains only six characters, so valid positive indexes are 0 through 5.
A safer approach is to check the length first:
1word = "Python" 2index = 10 3 4if 0 <= index < len(word): 5 print(word[index]) 6else: 7 print("Invalid index")
Output:
1Invalid index
3. Negative Indexing
Python also supports negative indexing.
Negative indexes start from the end of the string.
For "Python":
1Character: P y t h o n 2Positive: 0 1 2 3 4 5 3Negative: -6 -5 -4 -3 -2 -1
Therefore:
1word = "Python" 2 3print(word[-1]) 4print(word[-2]) 5print(word[-6])
Output:
1n 2o 3P
Negative indexing is especially useful when you need characters near the end of a string.
Practical Example
Get the last character of a username:
1username = "ankit123" 2 3print(username[-1])
Output:
13
You don't need to calculate len(username) - 1; -1 directly means the last character.
4. String Slicing
Slicing allows you to extract a portion of a string.
The basic syntax is:
1string[start:end]
The start index is included, but the end index is excluded.
Example
1word = "Python" 2 3print(word[0:2])
Output:
1Py
The indexes are:
1P y t h o n 20 1 2 3 4 5
word[0:2] includes indexes 0 and 1, but not 2.
Another Example
1word = "Python" 2 3print(word[2:5])
Output:
1tho
Slice from the Beginning
You can omit the starting index.
1word = "Python" 2 3print(word[:4])
Output:
1Pyth
This means:
1word[0:4]
Slice to the End
You can omit the ending index.
1word = "Python" 2 3print(word[2:])
Output:
1thon
Copy the Entire String
1word = "Python" 2 3print(word[:])
Output:
1Python
String Slicing with a Step
The extended slicing syntax is:
1string[start:end:step]
For example:
1word = "Python" 2 3print(word[::2])
Output:
1Pto
The program takes every second character.
Reverse a String
A negative step can be used to reverse a string.
1word = "Python" 2 3print(word[::-1])
Output:
1nohtyP
This is one of the most common Python techniques for reversing a string.
5. Important String Methods
Python provides many built-in string methods that make text processing easier.
A string method is called using dot notation:
1string.method()
For example:
1name = "python" 2 3print(name.upper())
Output:
1PYTHON
upper()
Converts all alphabetic characters to uppercase.
1name = "python programming" 2 3print(name.upper())
Output:
1PYTHON PROGRAMMING
lower()
Converts all alphabetic characters to lowercase.
1name = "PYTHON PROGRAMMING" 2 3print(name.lower())
Output:
1python programming
A common use case is normalizing user input:
1choice = input("Continue? ").strip().lower() 2 3if choice == "yes": 4 print("Continuing...")
This allows inputs such as "YES", "Yes", and "yes" to be handled consistently.
title()
Capitalizes the first letter of each word.
1text = "python programming language" 2 3print(text.title())
Output:
1Python Programming Language
This can be useful when displaying names or headings, although it should not be treated as a complete name-formatting solution for every language or naming convention.
capitalize()
Capitalizes the first character of a string and converts the remaining characters to lowercase.
1text = "pYTHON" 2 3print(text.capitalize())
Output:
1Python
replace()
The replace() method replaces one piece of text with another.
1text = "I love Java" 2 3result = text.replace("Java", "Python") 4 5print(result)
Output:
1I love Python
Replacing Multiple Occurrences
1sentence = "cat cat cat" 2 3print(sentence.replace("cat", "dog"))
Output:
1dog dog dog
You can also specify how many replacements should be performed:
1text = "one one one" 2 3print(text.replace("one", "two", 2))
Output:
1two two one
split()
The split() method divides a string into a list.
1text = "Python Java C++" 2 3languages = text.split() 4 5print(languages)
Output:
1['Python', 'Java', 'C++']
By default, split() separates text using whitespace.
Splitting by a Comma
1data = "Apple,Banana,Mango" 2 3fruits = data.split(",") 4 5print(fruits)
Output:
1['Apple', 'Banana', 'Mango']
join()
The join() method combines multiple strings into a single string.
1languages = ["Python", "Java", "C++"] 2 3result = ", ".join(languages) 4 5print(result)
Output:
1Python, Java, C++
Joining with a Hyphen
1numbers = ["1", "2", "3"] 2 3print("-".join(numbers))
Output:
11-2-3
A common beginner mistake is trying to join non-string values directly:
1numbers = [1, 2, 3] 2 3# TypeError 4print("-".join(numbers))
Convert them to strings first:
1numbers = [1, 2, 3] 2 3result = "-".join(str(number) for number in numbers) 4 5print(result)
Output:
11-2-3
strip()
Removes whitespace from the beginning and end of a string.
1text = " Python " 2 3print(text.strip())
Output:
1Python
This is especially useful when processing input from users.
1name = input("Enter your name: ").strip() 2 3print(f"Hello, {name}!")
lstrip()
Removes whitespace from the left side.
1text = " Hello" 2 3print(text.lstrip())
Output:
1Hello
rstrip()
Removes whitespace from the right side.
1text = "Hello " 2 3print(text.rstrip())
Output:
1Hello
count()
Counts how many times a substring occurs.
1text = "banana" 2 3print(text.count("a"))
Output:
13
Another example:
1text = "Python is easy. Python is powerful." 2 3print(text.count("Python"))
Output:
12
find()
Returns the index of the first occurrence of a substring.
1text = "Python Programming" 2 3print(text.find("Programming"))
Output:
17
If the substring does not exist, find() returns -1.
1text = "Python Programming" 2 3print(text.find("Java"))
Output:
1-1
This makes find() useful when you need the position of a substring.
in for Checking Text
You can use the in operator to check whether a substring exists.
1text = "Python Programming" 2 3if "Python" in text: 4 print("Python was found")
Output:
1Python was found
This is often clearer than using find() when you only need a True or False result.
startswith()
Checks whether a string starts with a particular value.
1url = "https://example.com" 2 3print(url.startswith("https://"))
Output:
1True
endswith()
Checks whether a string ends with a particular value.
1filename = "notes.pdf" 2 3print(filename.endswith(".pdf"))
Output:
1True
This can be useful for checking file extensions.
Character Validation Methods
Python provides several methods for checking the contents of strings.
isalpha()
Returns True if all characters are alphabetic and the string is not empty.
1text = "Python" 2 3print(text.isalpha())
Output:
1True
isdigit()
Checks whether all characters are digits.
1value = "12345" 2 3print(value.isdigit())
Output:
1True
isalnum()
Returns True when all characters are letters or numbers and the string is not empty.
1username = "Ankit123" 2 3print(username.isalnum())
Output:
1True
Note that _ is not considered alphanumeric:
1print("ankit_123".isalnum())
Output:
1False
6. String Formatting
String formatting allows you to insert variables and calculated values into text.
Python supports several formatting techniques, but f-strings are generally the recommended approach in modern Python code.
Using % Formatting
Older Python programs may use % formatting:
1name = "Ankit" 2 3print("Hello %s" % name)
Output:
1Hello Ankit
This style is still valid, but newer code generally prefers f-strings.
Using format()
The format() method provides another formatting approach.
1name = "Ankit" 2age = 22 3 4message = "My name is {} and I am {} years old.".format(name, age) 5 6print(message)
Output:
1My name is Ankit and I am 22 years old.
Named Formatting
1message = "Hello {user}, welcome to Python!".format( 2 user="Ankit" 3) 4 5print(message)
Output:
1Hello Ankit, welcome to Python!
7. f-Strings in Python
f-strings are one of the easiest and most readable ways to format strings.
An f-string starts with f before the opening quotation mark.
1name = "Ankit" 2age = 22 3 4print(f"My name is {name}.") 5print(f"I am {age} years old.")
Output:
1My name is Ankit. 2I am 22 years old.
Expressions Inside f-Strings
You can place Python expressions inside {}.
1a = 10 2b = 20 3 4print(f"Sum = {a + b}") 5print(f"Product = {a * b}")
Output:
1Sum = 30 2Product = 200
Formatting Decimal Numbers
Use a format specification after :.
1pi = 3.14159265 2 3print(f"{pi:.2f}")
Output:
13.14
The .2f means to display the number with two digits after the decimal point.
Formatting Currency
1price = 1499.5 2 3print(f"Price: ₹{price:,.2f}")
Output:
1Price: ₹1,499.50
Alignment
You can control text alignment inside a fixed-width field.
1name = "Python" 2 3print(f"|{name:<15}|") 4print(f"|{name:^15}|") 5print(f"|{name:>15}|")
Output:
1|Python | 2| Python | 3| Python|
The format specifiers mean:
<→ left-align^→ center-align>→ right-align
8. Escape Characters
Escape sequences allow you to represent special characters inside strings.
An escape sequence begins with a backslash (\).
| Escape Sequence | Meaning |
|---|---|
\n | New line |
\t | Tab |
\' | Single quote |
\" | Double quote |
\\ | Backslash |
New Line
1print("Hello\nPython")
Output:
1Hello 2Python
Tab
1print("Name\tAge") 2print("Ankit\t22")
Output:
1Name Age 2Ankit 22
Double Quotes Inside a String
1print("He said, \"Hello\"")
Output:
1He said, "Hello"
You can often avoid escaping by using different quotation marks:
1print('He said, "Hello"')
Backslash
1print("C:\\Users\\Ankit")
Output:
1C:\Users\Ankit
9. Raw Strings
A raw string treats most backslashes as literal characters instead of interpreting them as escape sequences.
Raw strings are commonly useful for Windows paths and regular expressions.
Syntax:
1r"string"
Example
1path = r"C:\Users\Ankit\Documents" 2 3print(path)
Output:
1C:\Users\Ankit\Documents
Without a raw string:
1path = "C:\new" 2 3print(path)
Here, \n is interpreted as a newline, so the result is not the intended Windows path.
A raw string avoids this interpretation:
1path = r"C:\new" 2 3print(path)
Output:
1C:\new
Important Raw String Note
A raw string cannot end with a single backslash.
For example, this is invalid:
1# Invalid 2path = r"C:\Users\"
Use a doubled backslash or another appropriate path-handling technique instead.
For real filesystem work, Python's pathlib is usually preferable to manually constructing paths:
1from pathlib import Path 2 3path = Path("C:/Users/Ankit/Documents") 4 5print(path)
10. Multiline Strings
Triple quotes can be used to create strings containing multiple lines.
1message = """Welcome to Python. 2 3This is Module 4. 4 5Happy Learning!""" 6 7print(message)
Output:
1Welcome to Python. 2 3This is Module 4. 4 5Happy Learning!
Multiline strings are useful for:
- Long messages
- Documentation
- Templates
- SQL statements
- Email content
- Large blocks of text
Useful String Methods
Here are some of the most useful string methods to remember:
| Method | Description |
|---|---|
upper() | Converts text to uppercase |
lower() | Converts text to lowercase |
title() | Capitalizes words |
capitalize() | Capitalizes the first character |
replace() | Replaces text |
split() | Converts a string into a list |
join() | Combines strings |
strip() | Removes surrounding whitespace |
lstrip() | Removes left-side whitespace |
rstrip() | Removes right-side whitespace |
count() | Counts occurrences |
find() | Finds the first matching index |
startswith() | Checks the beginning |
endswith() | Checks the ending |
isalpha() | Checks for alphabetic characters |
Strings Are Immutable
One of the most important concepts about Python strings is that they are immutable.
Immutable means that you cannot directly change an individual character after the string has been created.
For example:
1text = "Python" 2 3text[0] = "J"
This raises:
1TypeError: 'str' object does not support item assignment
Instead, create a new string.
1text = "Python" 2 3text = "J" + text[1:] 4 5print(text)
Output:
1Jython
String methods also return new strings rather than modifying the original string.
1text = "python" 2 3uppercase_text = text.upper() 4 5print(text) 6print(uppercase_text)
Output:
1python 2PYTHON
The original text remains unchanged.
Practice Project 1: Username Formatter
Problem
Create a program that:
- Takes a username from the user.
- Removes leading and trailing spaces.
- Converts the username to lowercase.
- Replaces spaces with underscores.
Solution
1username = input("Enter your username: ") 2 3username = username.strip() 4username = username.lower() 5username = username.replace(" ", "_") 6 7print(f"Formatted username: {username}")
Example:
1Enter your username: Ankit Kushwaha 2 3Formatted username: ankit_kushwaha
This project combines input(), strip(), lower(), and replace().
Practice Project 2: Basic Email Validator
Problem
Create a simple program that checks whether an email:
- Contains
@ - Ends with
.com
Solution
1email = input("Enter your email: ").strip().lower() 2 3if "@" in email and email.endswith(".com"): 4 print("Valid email") 5else: 6 print("Invalid email")
Example:
1Enter your email: ankit@gmail.com 2Valid email
Invalid example:
1Enter your email: ankitgmail 2Invalid email
Important Note
This is only a basic demonstration, not a complete email validation system. Real email validation has many additional rules.
Practice Project 3: Count Vowels
Create a program that counts the number of vowels in user input.
1text = input("Enter text: ").lower() 2 3vowels = "aeiou" 4count = 0 5 6for character in text: 7 if character in vowels: 8 count += 1 9 10print(f"Total vowels: {count}")
Example:
1Enter text: Python Programming 2Total vowels: 4
This example introduces an important pattern: iterating through each character of a string.
Practice Project 4: Palindrome Checker
A palindrome reads the same forward and backward.
Examples include:
1madam 2level 3racecar
Program:
1text = input("Enter a word: ").strip().lower() 2 3if text == text[::-1]: 4 print("Palindrome") 5else: 6 print("Not a palindrome")
Example:
1Enter a word: level 2Palindrome
Practice Project 5: Word Counter
The split() method can be used to count words.
1sentence = input("Enter a sentence: ").strip() 2 3words = sentence.split() 4 5print(f"Total words: {len(words)}")
Example:
1Enter a sentence: Python is easy to learn 2Total words: 5
Notice that split() without an argument handles consecutive whitespace more conveniently than manually splitting on " ".
Practice Project 6: Mask an Email Address
Create a simple program that hides most of the username portion of an email address.
1email = input("Enter your email: ").strip() 2 3parts = email.split("@") 4 5if len(parts) == 2 and parts[0]: 6 username, domain = parts 7 8 if len(username) <= 2: 9 masked_username = "*" * len(username) 10 else: 11 masked_username = username[:2] + "*" * (len(username) - 2) 12 13 print(f"Masked email: {masked_username}@{domain}") 14else: 15 print("Invalid email format")
Example:
1Enter your email: ankit@gmail.com 2Masked email: an****@gmail.com
This is a basic demonstration of string processing and should not be considered a complete privacy or email-validation system.
Common String Errors
1. Invalid Index
Incorrect:
1text = "Python" 2 3print(text[10])
The string does not contain index 10.
Correct:
1text = "Python" 2 3if len(text) > 0: 4 print(text[0])
2. Trying to Modify a String
Incorrect:
1text = "Python" 2 3text[0] = "J"
Strings are immutable.
Correct:
1text = "Python" 2text = "J" + text[1:] 3 4print(text)
Output:
1Jython
3. Forgetting That Slicing Excludes the End Index
Consider:
1word = "Python" 2 3print(word[0:2])
The result is:
1Py
Not:
1Pyt
The ending index 2 is excluded.
4. Confusing find() With a Boolean Check
If you only want to know whether text exists:
1text = "Python programming" 2 3print("Python" in text)
Output:
1True
If you need the position:
1print(text.find("Python"))
Output:
10
5. Forgetting That String Methods Return New Strings
This does not change text:
1text = "python" 2 3text.upper() 4 5print(text)
Output:
1python
Store the returned value:
1text = "python" 2 3text = text.upper() 4 5print(text)
Output:
1PYTHON
Practice Exercises
Exercise 1: Reverse a String
Write a program that accepts a string and prints it in reverse.
Expected technique:
1text[::-1]
Exercise 2: Count Vowels
Ask the user for a sentence and count the number of vowels.
Try to handle both uppercase and lowercase letters.
Exercise 3: Palindrome Checker
Create a program that determines whether a word is a palindrome.
Bonus: make the comparison case-insensitive.
Exercise 4: Word Counter
Ask the user for a sentence and display the total number of words.
Use:
1split()
Exercise 5: Character Counter
Ask the user for a string and a character, then count how many times that character appears.
Example:
1Enter text: banana 2Enter character: a 3Occurrences: 3
Exercise 6: Username Validator
Create a program that checks whether a username:
- Contains only letters and numbers
- Is between 5 and 15 characters
- Does not contain spaces
Useful methods:
1isalnum() 2len()
Exercise 7: File Extension Checker
Ask the user for a filename and determine whether it is a .pdf, .txt, or .py file.
Use:
1endswith()
Quick Quiz
- What is the data type used to store text in Python?
- What index does the first character of a string have?
- What does
word[-1]return? - What is the difference between
word[1:4]andword[:4]? - Does slicing include the ending index?
- What does
split()return? - What does
join()do? - Why is
strip()useful when processing user input? - Why are f-strings commonly preferred for modern string formatting?
- Are Python strings mutable or immutable?
- What does
find()return when the substring is not found? - What is the purpose of a raw string?
- What does
[::-1]do? - What is the difference between
upper()andlower()? - What does
indo when used with a string?
Module Summary
In this module, you learned how Python handles text using strings.
The most important concepts are:
- Strings are sequences of characters.
- Python supports single, double, and triple-quoted strings.
- String indexes start from
0. - Negative indexes start from
-1at the end. - Slicing extracts a portion of a string.
- The ending index in a slice is excluded.
[::-1]can reverse a string.- String methods such as
upper(),lower(),replace(),split(),join(), andstrip()simplify text processing. startswith()andendswith()are useful for prefix and suffix checks.incan check whether text exists inside another string.- f-strings provide a readable way to insert values into strings.
- Escape sequences represent special characters.
- Raw strings are useful when backslashes need to be treated literally.
- Python strings are immutable.
- String processing is essential for real-world applications.
Mastering strings is an important step toward learning Python's control flow, collections, functions, file handling, web development, data processing, and automation.
What's Next?
In the next module, you can learn about Python Lists.
Lists allow you to store multiple values in a single variable and are one of the most commonly used collection types in Python.