Get 60% off lifetime access &
job ready curriculum guide

YOU WILL RECEIVE DISCOUNT CODE AND THE GUIDE INTO YOUR EMAIL AFTER SIGNING UP

    We don’t send spam. Unsubscribe anytime.

    Author

    “Your course helped me get my job as a software engineer at Charles Schwab. The course was easy to follow and covered all the material I'd need to nail a leetcode style interview. Thank you!”

    - Mohammed Khan
    Strings in Python: Indexing and Slicing for Beginners

    Strings in Python: Indexing and Slicing for Beginners

    December 13, 2024 by Imtiaz Ahmad

    Table of Contents

    Strings in Python are a cornerstone of programming, and Python makes working with them incredibly flexible. In this guide, we’ll explore some fundamental concepts of working with strings, including indexing, slicing, and how to handle common challenges. Whether you’re a complete beginner or brushing up on your skills, this guide will equip you with the tools to manipulate and extract data from strings effortlessly.


    Getting Started with Strings in Python

    In Python, a string is simply a sequence of characters enclosed in either single (') or double (") quotes. Both styles work interchangeably, but you’ll need to choose the appropriate one when handling specific cases like apostrophes.

    Example: Handling Apostrophes in Strings

    # Using single quotes
    sentence = 'This is a sentence.'
    print(sentence)  # Output: This is a sentence.
    
    # Handling an apostrophe
    sentence_with_apostrophe = "I'm coming home"
    print(sentence_with_apostrophe)  # Output: I'm coming home

    Using double quotes (") avoids errors when your string includes an apostrophe (').


    Escape Sequences

    Escape sequences let you control how strings are printed. For instance, n represents a new line. Let’s look at an example:

    # Using n to print text on separate lines
    sentence = "I'm comingnhome"
    print(sentence)

    Output:

    I'm coming
    home

    Notice the n creates a new line. Avoid spaces after n unless you intentionally want them.


    Indexing in Strings

    Every character in a Python string has a unique index. Indexing starts at 0 for the first character and continues sequentially. Additionally, you can use negative indexing to count backward, starting from -1.

    Example: Accessing Characters by Index

    sentence = "This is a sentence"
    
    # Positive indexing
    print(sentence[0])  # Output: T
    print(sentence[3])  # Output: s
    
    # Negative indexing
    print(sentence[-1])  # Output: e
    print(sentence[-3])  # Output: c

    Using negative indexes is a handy way to access characters without counting the total length.


    Slicing Strings

    Slicing allows you to extract substrings (a portion of the string) by specifying a range of indexes. The syntax for slicing is:

    string[start:end]
    • start: The index to begin the slice (inclusive).
    • end: The index to stop at (exclusive).

    Example: Basic Slicing

    sentence = "This is a sentence"
    
    # Extracting "This"
    print(sentence[0:4])  # Output: This
    
    # Extracting "is"
    print(sentence[5:7])  # Output: is

    If the start index is omitted, slicing begins at the start of the string. Similarly, if the end index is omitted, it slices until the end of the string.

    # Slicing from the start
    print(sentence[:4])  # Output: This
    
    # Slicing to the end
    print(sentence[10:])  # Output: sentence

    Skipping Characters in Slices

    You can add a third value, called a step, to specify how many characters to skip.

    # Syntax: string[start:end:step]
    sentence = "abcdefg"
    
    # Extract every second character
    print(sentence[0:7:2])  # Output: aceg

    If you only want to slice from a given index to the end while skipping characters, simply omit the end value.


    Reversing a String

    You can reverse a string by using slicing with a step of -1.

    sentence = "abcdefg"
    
    # Reverse the string
    print(sentence[::-1])  # Output: gfedcba
    

    Practice Challenge

    Try extracting the word is from the string below:

    sentence = "This is a sentence"

    Hint: Identify the indexes of the first letter (i) and the position right after the last letter (s). Don’t forget that the second index in slicing is exclusive!


    Resources

    • Join Job Ready Programmer Courses and gain mastery in Data Analytics & Software Development.
    • Access our free Programming Guide (PDF) to explore our comprehensive Job Ready Curriculum today!
    • Check out the Free Python Basics Lecture Series on Job Ready Programmer’s YouTube Channel.
    • Special Discount: 20% Off PyCharm Professional IDE 
      • Use the promo code “JRP_ProPyPath_24” on this JetBrains Checkout Page: JetBrains Store
      • Use this code and get a 20% discount on a PyCharm Professional IDE license, valid until February 5, 2025. 
      • We recommend this for our learners to explore more advanced features. 
      • Note: The entire crash course series can be followed using the free PyCharm Community version.
    • Watch the following free lecture on the Strings in Python:

    Wrapping Up

    String manipulation in Python is powerful and straightforward once you master the basics of indexing and slicing. Whether you’re extracting specific characters, creating substrings, or skipping characters, these techniques provide a strong foundation for handling text data.

    Subscribe

      We do not send spam. Unsubscribe anytime.
      Back to blog
      Self Improvement | Software Development
      Discouraged While Learning Software Development?

      So, are you someone who is trying to learn something new like software development, and feels discouraged? Well, trust me, you are not alone. I get these reactions from students saying that: “I have been learning this skill for a month now, and it’s not registering” “I have learned this but then I forget what […]

      Imtiaz Ahmad
      Data Analytics | Personal Branding
      How to boost your LinkedIn Profile?

      In this blog, we will look into several tips that will help you increase your LinkedIn profile’s visibility and keep it professional. Importance of profile picture To begin, let’s understand why it’s so important to have a profile picture on your LinkedIn profile. If someone looks at your profile and sees your profile picture blank, […]

      Imtiaz Ahmad
      Self Improvement | Software Development
      Top 5 Self Improvement Hacks

      In this blog, I want to give you five Self Improvement hacks that will help you improve your life and make you into a better version of yourself. And these are hacks that have changed my life which I use every day. Hack 1 – Reflex Retraining We’ll start with the first one which is […]

      Imtiaz Ahmad