Nearby lessons

56 of 108

Python - 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 3 Runtime
Loading Editor...
Output Preview
python

Using double quotes:

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
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
Python 3 Runtime
Loading Editor...
Output Preview
Welcome to Python
🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
Python Programming Language

Using Quotes Inside Strings

Triple quotes allow us to use quotes inside strings easily.

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
This is "Python" class
🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
This is 'Python' class

String Indexing

Strings support indexing and Python uses zero-based indexing.

Character Positive Index Negative Index
d0-5
u1-4
r2-3
g3-2
a4-1
🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
d
u
a

Index Out of Range

If the index exceeds the string range, IndexError occurs.

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
IndexError: string index out of range

String Slicing

Slice means a piece of a string.

Syntax: string[start:end]

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
yth
pyth
ython
python

String Repetition and Length

Strings can be repeated using the * operator.

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
pythonpythonpython

len() is used to find the length of a string.

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
6

Membership, Concatenation, and Immutability

We can use membership operators in and not in.

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
True
False

Strings can be combined using the + operator.

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
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 3 Runtime
Loading Editor...
Output Preview
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
Python 3 Runtime
Loading Editor...
Output Preview
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
Python 3 Runtime
Loading Editor...
Output Preview
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
Python 3 Runtime
Loading Editor...
Output Preview
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
Python 3 Runtime
Loading Editor...
Output Preview
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
Python 3 Runtime
Loading Editor...
Output Preview
['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
Python 3 Runtime
Loading Editor...
Output Preview
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
Python 3 Runtime
Loading Editor...
Output Preview
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
Python 3 Runtime
Loading Editor...
Output Preview
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
Python 3 Runtime
Loading Editor...
Output Preview
agrud

Reverse Order of Words

We can reverse the order of words by splitting, traversing in reverse, and joining again.

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
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(), and replace() 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 Typestr
MutableNo
Supports IndexingYes
Supports SlicingYes
Supports RepetitionYes
Quotes SupportedSingle, Double, Triple
Common Methodsstrip, find, count, replace, split, join, startswith, endswith
Character Checksisalnum, isalpha, isdigit, islower, isupper, isspace, istitle
Case Conversionupper, lower, swapcase, title, capitalize

🧠 Test Your Knowledge

4 Questions

Progress: 0 / 4
Keep Going!Python - String Indexing