Comprehensive Notes on Python Strings
These notes provide a detailed explanation of strings in Python, including types, properties, built■in
functions, and example programs useful for computer science students.
1. Introduction to Python Strings
• A string is a sequence of characters used to store text.
• In Python, strings are enclosed in single quotes, double quotes, or triple quotes.
• Strings are immutable, meaning they cannot be modified after creation.
• Each character in a string has an index position.
2. Types of Strings in Python
• Single■quoted strings: 'Hello'
• Double■quoted strings: "Hello"
• Triple■quoted strings for multi■line text.
• Raw strings using r prefix to ignore escape characters.
• Formatted strings (f■strings) to insert variables into text.
3. Important Properties of Strings
• Indexing: Access characters using positions like text[0].
• Slicing: Extract parts of a string using text[start:end].
• Immutability: String characters cannot be changed directly.
• Concatenation: Strings can be joined using the + operator.
• Repetition: Strings can be repeated using the * operator.
4. Important Built■in String Functions
Function Description Example
upper() Convert string to uppercase 'python'.upper()
lower() Convert string to lowercase 'HELLO'.lower()
capitalize() Capitalize first letter 'python'.capitalize()
title() Capitalize each word 'python language'.title()
strip() Remove spaces from both ends ' hello '.strip()
lstrip() Remove spaces from left ' hello'.lstrip()
rstrip() Remove spaces from right 'hello '.rstrip()
replace() Replace substring 'I like Java'.replace('Java','Python')
split() Split string into list 'Python is easy'.split()
join() Join list elements ' '.join(['Python','is','fun'])
find() Return first index of substring 'python'.find('t')
count() Count occurrences 'banana'.count('a')
startswith() Check start of string 'Python'.startswith('Py')
endswith() Check end of string '[Link]'.endswith('.txt')
isalpha() Check alphabet characters 'Python'.isalpha()
isdigit() Check digits '12345'.isdigit()
isalnum() Check letters and digits 'Python123'.isalnum()
len() Length of string len('Python')
5. Example Programs Using Strings
• Program 1: Reverse a string using slicing.
• Program 2: Count vowels in a string.
• Program 3: Check whether a string is a palindrome.
• Program 4: Convert a sentence into a list of words.
• Program 5: Replace a word in a sentence.
• Program 6: Check whether a string contains only numbers.
• Program 7: Find the length of a string.
• Program 8: Convert user input to uppercase.
• Program 9: Join list elements into a sentence.
• Program 10: Find frequency of a character.
6. Conclusion
Python strings are fundamental for text processing and data manipulation. Understanding indexing,
slicing, and built■in methods is essential for programming, exams, and software development
tasks.