Paramclasses Academy - Blog

Tutorials Details

←
Post 7 of 20
→

Python Strings: Indexing, Slicing, Methods & Examples

Python Strings: Indexing, Slicing, Methods & Examples

October 17, 2026

Python Strings: Indexing, Slicing, Methods & Examples

1. Introduction to Python Strings

A string in Python is a sequence of characters used to store text. It can contain letters, numbers, symbols, spaces, and special characters.

Strings are one of the most commonly used data types in Python. They are useful for storing names, addresses, messages, email IDs, product names, and other text-based information.

Example

name = "Rahul"
message = "Welcome to Python Programming!"

print(name)
print(message)

Output:

Rahul
Welcome to Python Programming!

2. Creating Strings in Python

Python allows you to create strings using single quotes, double quotes, or triple quotes.

Single Quotes

name = 'Rahul'
print(name)

Double Quotes

city = "Raipur"
print(city)

Triple Quotes

Triple quotes can be used for multiline strings.

message = """Welcome to Python.
Learn programming step by step."""
print(message)

Output:

Welcome to Python.
Learn programming step by step.

3. Accessing Characters Using Indexing

String indexing allows you to access individual characters by their positions.

Python indexing starts at 0. The first character has index 0, the second has index 1, and so on.

word = "PYTHON"

print(word[0])
print(word[1])
print(word[5])

Output:

P
Y
N

Negative Indexing

Negative indexing accesses characters from the end of a string. The last character has index -1.

word = "PYTHON"

print(word[-1])
print(word[-2])

Output:

N
O

Key Point: Accessing an index that does not exist raises an IndexError.

4. String Slicing in Python

String slicing extracts a portion of a string.

Syntax

string[start:stop:step]
  • start: Index where slicing begins.

  • stop: Index where slicing ends; the stop index is excluded.

  • step: Number of positions to move each time.

Example 1: Basic Slicing

text = "PYTHON"

print(text[0:3])
print(text[2:6])

Output:

PYT
THON

Example 2: Omitting Start and Stop

text = "PYTHON"

print(text[:3])
print(text[3:])
print(text[:])

Output:

PYT
HON
PYTHON

Example 3: Reverse a String

text = "PYTHON"
print(text[::-1])

Output:

NOHTYP

5. String Immutability

Python strings are immutable, which means their individual characters cannot be changed after the string is created.

The following code causes a TypeError:

text = "Python"
text[0] = "J"

To create a modified string, use a new string value.

text = "Python"
text = "J" + text[1:]

print(text)

Output:

Jython

6. Important Python String Methods

Python provides built-in string methods for common text operations.

upper()

Converts all letters to uppercase.

text = "python"
print(text.upper())

Output: PYTHON

lower()

Converts all letters to lowercase.

text = "PYTHON"
print(text.lower())

Output: python

title()

Converts the first character of each word to uppercase.

text = "learn python programming"
print(text.title())

Output: Learn Python Programming

capitalize()

Capitalizes the first character of the string and lowercases the remaining characters.

text = "hELLO WORLD"
print(text.capitalize())

Output: Hello world

strip()

Removes whitespace from both ends of a string.

text = "   Python   "
print(text.strip())

Output: Python

replace()

Replaces one substring with another.

text = "I like Java"
print(text.replace("Java", "Python"))

Output: I like Python

split()

Splits a string into a list of strings.

text = "HTML,CSS,Python"
print(text.split(","))

Output:

['HTML', 'CSS', 'Python']

join()

Joins strings from an iterable using a separator.

languages = ["HTML", "CSS", "Python"]
print(", ".join(languages))

Output: HTML, CSS, Python

7. Searching Within Strings

Python provides methods to search for text inside a string.

find()

Returns the index of the first occurrence of a substring. It returns -1 if the substring is not found.

text = "Learn Python Programming"

print(text.find("Python"))
print(text.find("Java"))

Output:

6
-1

count()

Counts how many times a substring occurs.

text = "banana"
print(text.count("a"))

Output: 3

startswith() and endswith()

These methods check how a string begins or ends.

filename = "report.pdf"

print(filename.startswith("report"))
print(filename.endswith(".pdf"))

Output:

True
True

8. Checking String Content

Python provides useful methods to check the contents of strings.

print("Python".isalpha())
print("12345".isdigit())
print("Python123".isalnum())
print("hello".islower())
print("HELLO".isupper())

Output:

True
True
True
True
True
  • isalpha() checks whether all characters are alphabetic.

  • isdigit() checks whether all characters are digits.

  • isalnum() checks whether all characters are letters or digits.

  • islower() checks whether cased letters are lowercase.

  • isupper() checks whether cased letters are uppercase.

These methods return Boolean values: True or False.

9. String Concatenation

Concatenation means joining strings using the + operator.

first_name = "Rahul"
last_name = "Sharma"

full_name = first_name + " " + last_name

print(full_name)

Output:

Rahul Sharma

The + operator joins strings, but it does not automatically convert numbers into strings.

age = 22
print("Age: " + str(age))

Output: Age: 22

10. String Repetition

The * operator repeats a string a specified number of times.

text = "Python "

print(text * 3)

Output:

Python Python Python

11. String Formatting

String formatting allows you to insert variables into text.

Using f-Strings

F-strings are a readable and convenient way to format strings in modern Python.

name = "Rahul"
age = 22

print(f"My name is {name} and I am {age} years old.")

Output:

My name is Rahul and I am 22 years old.

Formatting Numbers

price = 1250.567

print(f"Price: {price:.2f}")

Output:

Price: 1250.57

The .2f format displays two digits after the decimal point.

12. Escape Characters

Escape characters represent special characters inside strings.

Escape Character Meaning
\n New line
\t Horizontal tab
\\ Backslash
\' Single quote
\" Double quote

Example

print("Hello\nWorld")
print("Name:\tRahul")
print("It's Python")

Output:

Hello
World
Name:   Rahul
It's Python

13. Practical Project: Name Formatter

Create a program that accepts a user's name, removes extra spaces, and displays the name in title case.

name = input("Enter your full name: ")

formatted_name = name.strip().title()

print("Formatted Name:", formatted_name)

Sample Input:

   rahul sharma

Sample Output:

Enter your full name:    rahul sharma
Formatted Name: Rahul Sharma

Explanation:

  • input() accepts the name from the user.

  • strip() removes extra whitespace from the beginning and end.

  • title() capitalizes the first character of each word.

14. Practical Project: Email Validator

The following program performs basic checks on an email address.

email = input("Enter your email: ").strip()

if "@" in email and "." in email and " " not in email:
    print("Basic email check passed.")
else:
    print("Please enter a valid email format.")

Sample Input:

rahul@example.com

Output:

Basic email check passed.

Important: This is only a basic format check, not complete email validation. Real applications should use more robust validation and, when necessary, email verification.

15. Practical Project: Word and Character Counter

This program counts characters, characters excluding spaces, words, and vowels in a sentence.

text = input("Enter a sentence: ")

character_count = len(text)
characters_without_spaces = len(text.replace(" ", ""))
words = len(text.split())

vowels = 0

for char in text.lower():
    if char in "aeiou":
        vowels += 1

print("Total characters:", character_count)
print("Characters without spaces:", characters_without_spaces)
print("Total words:", words)
print("Total vowels:", vowels)

Sample Input:

Learn Python

Output:

Total characters: 12
Characters without spaces: 11
Total words: 2
Total vowels: 3

16. Common Mistakes in Python Strings

Mistake 1: Using an invalid index

text = "Python"
print(text[10])

This raises an IndexError because the index is outside the string's range.

Mistake 2: Trying to modify a character directly

text = "Python"
text[0] = "J"

Strings are immutable, so this raises a TypeError.

Mistake 3: Mixing strings and integers

age = 22
print("Age: " + age)

This raises a TypeError. Convert the number with str(age) or use an f-string.

Correct approach:

age = 22
print(f"Age: {age}")

Mistake 4: Forgetting that the stop index is excluded

text = "Python"
print(text[0:3])

Output: Pyt

The slice includes indexes 0, 1, and 2, but not index 3.

Mistake 5: Assuming string methods change the original string

text = "python"
text.upper()

print(text)

Output: python

String methods return a new string. To keep the changed value, assign the result:

text = text.upper()
print(text)

Output: PYTHON

17. Practice Programs

Try solving these programs using Python strings:

  1. Print the first and last characters of a string.

  2. Reverse a string using slicing.

  3. Count the number of characters in a sentence.

  4. Convert a sentence to uppercase.

  5. Convert a sentence to lowercase.

  6. Replace spaces with hyphens.

  7. Count the occurrences of a specific character.

  8. Check whether a word starts with a particular letter.

  9. Remove extra spaces from both ends of a string.

  10. Count the words in a sentence.

  11. Check whether a string contains only digits.

  12. Join a list of words into one sentence.

  13. Format a user's full name.

  14. Count the vowels in a word.

  15. Check whether a string is a palindrome.

18. Quiz: Test Your Knowledge

Q1. What is a string in Python?

Answer: A string is a sequence of characters used to represent text.

Q2. Which index represents the first character?

Answer: Index 0.

Q3. What does upper() do?

Answer: It returns a string with all cased letters converted to uppercase.

Q4. What is the output of "Python"[::-1]?

Answer: nohtyP

Q5. Are Python strings mutable?

Answer: No. Python strings are immutable.

Q6. What does strip() do?

Answer: It removes whitespace from both ends of a string by default.

Q7. What does split() return?

Answer: A list of strings.

Q8. Which method searches for a substring and returns -1 when it is not found?

Answer: find().

Q9. What is the output of "ha" * 3?

Answer: hahaha

Q10. Which is a convenient modern way to insert variables into a string?

Answer: An f-string, such as f"Hello, {name}".

19. Assignment

Build a Student Information Formatter that:

  1. Accepts the student's full name, course name, and email address.

  2. Removes extra spaces from the inputs.

  3. Formats the student's name using title().

  4. Displays the course name in uppercase.

  5. Counts the characters in the student's name.

  6. Checks whether the email contains @ and a dot.

  7. Displays all information using f-strings.

Expected Result: The program should display neatly formatted student information and a basic email-format check.

20. Summary

In this tutorial, you learned:

  • How to create strings using different quotation styles.

  • Positive and negative string indexing.

  • String slicing and reversing.

  • String immutability.

  • Important methods such as upper(), lower(), strip(), replace(), split(), and join().

  • Searching with find() and counting with count().

  • String concatenation and repetition.

  • Formatting text with f-strings.

  • Escape characters and practical string-based projects.

  • Common mistakes, practice programs, and quiz questions.

Conclusion: Python strings are essential for handling text in applications, websites, data processing, and automation. Practising indexing, slicing, and string methods will help you write more effective Python programs.

←
Post 7 of 20
→