Nearby lessons
56 of 108Python - Strings
What Is a String?
A string is a sequence of characters enclosed within single quotes or double quotes. Strings are used to represent text data in Python.
Creating Strings
Using single quotes:
main.py
python
Using double quotes:
main.py
python
Multi-line Strings
Single quotes and double quotes cannot represent multi-line strings.
For multi-line strings, use triple single quotes or triple double quotes.
main.py
Welcome to Python
main.py
Python Programming Language
Using Quotes Inside Strings
Triple quotes allow us to use quotes inside strings easily.
main.py
This is "Python" class
main.py
This is 'Python' class
String Indexing
Strings support indexing and Python uses zero-based indexing.
| Character | Positive Index | Negative Index |
|---|---|---|
| d | 0 | -5 |
| u | 1 | -4 |
| r | 2 | -3 |
| g | 3 | -2 |
| a | 4 | -1 |
main.py
d u a
Index Out of Range
If the index exceeds the string range, IndexError occurs.
main.py
IndexError: string index out of range
String Slicing
Slice means a piece of a string.
Syntax: string[start:end]
main.py
yth pyth ython python
String Repetition and Length
Strings can be repeated using the * operator.
main.py
pythonpythonpython
len() is used to find the length of a string.
main.py
6
Membership, Concatenation, and Immutability
We can use membership operators in and not in.
main.py
True False
Strings can be combined using the + operator.
main.py
Hello Python
Strings are immutable, so characters cannot be modified directly.
Iteration and Escape Characters
We can iterate through a string using a loop.
main.py
python
Escape characters are represented using backslash (\).
print("Hello\nPython")
print("Hello\tPython")Removing Spaces from a String
Python provides three methods to remove spaces from a string.
rstrip()removes spaces from the right side.lstrip()removes spaces from the left side.strip()removes spaces from both sides.
main.py
Enter your city Name: Hyderabad Hello Hyderabadi. Adab Enter your city Name: Chennai Hello Madrasi. Vanakkam Enter your city Name: Mumbai your entered city is invalid
Finding Substrings
Python provides find(), index(), rfind(), and rindex() to search for substrings.
find() returns -1 if the substring is not found.
index() raises ValueError if the substring is not found.
rfind() and rindex() search from the right side.
main.py
9 -1 9
Difference Between find() and index()
| find() | index() |
|---|---|
| Returns the index of the first occurrence. | Returns the index of the first occurrence. |
Returns -1 if the substring is not found. | Raises ValueError if the substring is not found. |
main.py
ValueError: substring not found
Counting and Replacing
The count() method counts the number of occurrences of a substring.
The replace() method replaces one substring with another.
main.py
3 Learning Python is very simple
Splitting and Joining
The split() method converts a string into a list.
The join() method joins a sequence of strings into one string.
main.py
['Learning', 'Python', 'is', 'very', 'easy'] Learning Python is very easy
startswith() and endswith()
startswith() checks whether a string begins with a given substring.
endswith() checks whether a string ends with a given substring.
main.py
True True
Character Checking Methods
String methods can check whether a string contains only a certain type of characters.
| Method | Description |
|---|---|
isalnum() | Checks whether all characters are alphanumeric |
isalpha() | Checks whether all characters are alphabets |
isdigit() | Checks whether all characters are digits |
islower() | Checks whether all alphabet characters are lowercase |
isupper() | Checks whether all alphabet characters are uppercase |
isspace() | Checks whether all characters are spaces |
istitle() | Checks whether the string is in title case |
main.py
True True True True True True True
Case Conversion Methods
Case conversion methods create a new string and leave the original unchanged.
| Method | Purpose |
|---|---|
upper() | Converts all characters to uppercase |
lower() | Converts all characters to lowercase |
swapcase() | Converts uppercase to lowercase and lowercase to uppercase |
title() | Converts the first character of every word to uppercase |
capitalize() | Converts only the first character of the string to uppercase |
main.py
LEARNING PYTHON Learning Python Learning python python pYtHoN
Reverse a String
A string can be reversed using slicing, reversed(), or a while loop.
main.py
agrud
Reverse Order of Words
We can reverse the order of words by splitting, traversing in reverse, and joining again.
main.py
easy!! very is Python Learning
Important Notes
- Strings are immutable.
- Indexing and slicing are supported.
- Strings can use single, double, or triple quotes.
- Strings support concatenation and repetition.
- String methods like
strip(),find(), andreplace()return new values.
Real World Usage
Strings are used for usernames, passwords, messages, file names, web URLs, data processing, validation, and formatting.
Summary
| Feature | Description |
|---|---|
| Data Type | str |
| Mutable | No |
| Supports Indexing | Yes |
| Supports Slicing | Yes |
| Supports Repetition | Yes |
| Quotes Supported | Single, Double, Triple |
| Common Methods | strip, find, count, replace, split, join, startswith, endswith |
| Character Checks | isalnum, isalpha, isdigit, islower, isupper, isspace, istitle |
| Case Conversion | upper, lower, swapcase, title, capitalize |