• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

The Programming Expert

Solving All of Your Programming Headaches

  • HTML
  • JavaScript
  • jQuery
  • PHP
  • Python
  • SAS
  • Ruby
  • About
You are here: Home / Python / Get Substring from String in Python with String Slicing

Get Substring from String in Python with String Slicing

October 6, 2022 Leave a Comment

To get a substring of a string variable in Python, you can use string slicing and specify the start point and end point of your substring.

string = "example"

print(string[0])   #first character
print(string[:4])  #first 4 characters
print(string[1:4]) #characters 2-4
print(string[2:])  #all characters after the 2nd character
print(string[-2:]) #last two characters
print(string[:-2]) #all characters until the 2nd to last character

#Output:
e
exam
xam
ample
le
examp

When working with variables of different types, the ability to modify and change the values easily is very useful.

One such case is if you are working with strings and want to create a substring from that string.

To get a substring of a string variable in Python, you can use string slicing and specify the start point and end point of your substring. Python is a zero-index based language and therefore, the first character of a string has index 0 and the end index is the length of the string minus 1.

You can pass positive and negative values for these starting and ending points given they are between 0 and the length of the string minus 1.

You also can leave out a value for the starting or ending point and then the substring will start at the beginning or end respectively.

Below are some simple examples of how you can use string slicing to get a substring of a string in Python.

string = "example"

print(string[0])   #first character
print(string[:4])  #first 4 characters
print(string[1:4]) #characters 2-4
print(string[2:])  #all characters after the 2nd character
print(string[-2:]) #last two characters
print(string[:-2]) #all characters until the 2nd to last character

#Output:
e
exam
xam
ample
le
examp

Using String Slicing to Get Substrings of Strings in Python

As shown above, there are a number of different ways you can use string slicing to get substrings of a string in Python.

There are a few cases I want to call out here so that you can understand all of the ways you can use string slicing in Python.

The first is if you want to get the first N characters of a string. To get the first N characters of a string, leave out the starting point and then pass N for the ending point.

Below is an example showing you how to get the first N characters of a string using string slicing in Python.

string = "example"

print(string[:4])  #first 4 characters

#Output:
exam

The second case is if you want to get the slice to the end of a string in Python. To slice until the end, then leave out the ending point. Then, just specify the starting point for your substring as you would normally do.

Below is an example showing you how to slice to the end of a string using string slicing in Python.

string = "example"

print(string[3:])  #all characters after the 3rd character

#Output:
mple

You can also use negative indexing to create substrings with string slicing in Python. For example, if you wanted to get the last N characters, you could modify the last example and pass -N as the starting point.

Below is an example showing you how to get the last N characters of a string using string slicing in Python.

string = "example"

print(string[-4:])  #all characters after the 3rd character

#Output:
mple

Remove First and Last Character from String Using Python

One useful example of using string slicing is if you want to create a substring which removes the first and last character from a string.

With slicing, we can easily get rid of the first and last character from a string. To do so, we need to select all of the elements between the first and last character.

To keep everything between the first and last character, we should pass ‘1’ as the start position and ‘-1’ as the end position to create our slice.

Below is how we can truncate a string and remove the first and last character from a string in Python.

string = "This is a string variable"

string_without_first_last_char = string[1:-1]

print(string_without_first_last_char)

#Output:
his is a string variabl

Get Substring Between Two Characters with Python

When working with strings in Python, the ability to extract pieces of information from those strings can be valuable.

One such piece of information which can be useful is a substring between two characters.

With Python, you can easily get the characters between two characters using the string index() function and string slicing.

First, you need to get the position of each of the two characters. Then we can create a slice to get the characters between the two positions.

Below is a simple example of how you can get the substring between two characters in Python.

string = "Word1aWord2bWord3"

between_a_and_b = string[string.index("a") + 1: string.index("b")]

print(between_a_and_b)

#Output:
Word2

Get All Substrings of a String in Python

When working with string variables, the ability to easily create new objects from those strings can be very useful.

One such case is if you want to get all substrings of a string variable in your Python code.

To get all substrings of a string in Python, the easiest way is with list comprehension and string slicing.

With list comprehension, we will loop over all combinations of positions of our string and get all of the substrings using slicing.

Below is a simple example showing how you can get all substrings of a string in Python.

string = "example"

all_substrings = [string[i:j] for i in range(len(string)) for j in range(i + 1, len(string) + 1)]

print(all_substrings)

#Output:
['e', 'ex', 'exa', 'exam', 'examp', 'exampl', 'example',
 'x', 'xa', 'xam', 'xamp', 'xampl', 'xample', 'a', 'am', 'amp', 'ampl', 'ample', 
 'm', 'mp', 'mpl', 'mple', 'p', 'pl', 'ple', 'l', 'le', 'e']

Hopefully this article has been useful for you to learn how to get substrings from strings in Python.

Other Articles You'll Also Like:

  • 1.  Read Last N Lines of File in Python
  • 2.  Zip Two Lists in Python
  • 3.  How to Group By Columns and Find Sum in pandas DataFrame
  • 4.  How to Sort Numbers in Python Without Sort Function
  • 5.  Python acos – Find Arccosine and Inverse Cosine of Number
  • 6.  How to Split a String in Half Using Python
  • 7.  pandas T Function – Transposing DataFrames with pandas
  • 8.  Find Last Occurrence in String of Character or Substring in Python
  • 9.  Change Python Turtle Shape Fill Color with fillcolor() Function
  • 10.  Length of Set Python – Get Set Length with Python len() Function

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

About The Programming Expert

the programming expert main image

Welcome to The Programming Expert. We are a group of US-based programming professionals who have helped companies build, maintain, and improve everything from simple websites to large-scale projects.

We built The Programming Expert to help you solve your programming problems with useful coding methods and functions in various programming languages.

Search

Learn Coding from Experts on Udemy

Looking to boost your skills and learn how to become a programming expert?

Check out the links below to view Udemy courses for learning to program in the following languages:

Copyright © 2023 · The Programming Expert · About · Privacy Policy