Python – Get Substrings of a String

This is a quick tutorial on how you can generate different types of substrings from an existing string in python using the string slicing method.

Getting Different Substrings Of A String In Python

Consider the following code. I’ve stored my name in a string variable fullString. Now, the following lines of code illustrate how you can get different types of substrings of the full String stored in this variable.

SubStrings According To Starting & Ending Positions

fullString = "Gurmeet Singh"

#Slice First 3 Characters
subString1 = fullString[3:]
print(subString1)

#Only Get First 3 Characters
subString2 = fullString[:3]
print(subString2)

#Remove Last 3 Characters
subString3 = fullString[:-3]
print(subString3)

#Only Get Last 3 Characters
subString4 = fullString[-3:]
print(subString4)

#Slice First 3 and Last 3 Characters
subString5 = fullString[3:-3]
print(subString5)

The output of the above code is shown in the following screenshot.

Python Substrings Program

Alternate Characters Substrings

You can also use the same slicing concept in python to generate substrings by forming a lot more logic. The following lines of code will help you form a string by choosing the alternate string characters.

fullString = "Alternate Characters"
#Choose Alternate Characters & Forms the SubString
subString = fullString[::2] #Basically we're selecing every 2nd chracter
print(subString)

Output.

Substring From Alternate Characters In Python

As in the above code, we’re selecting every second character from the string to form its substring, you can specify any number in the splicing argument to the required substring from the full string.

Bonus Tip to Reverse String or SubString

This concept of forming substrings from python strings can also be used to generate reverse strings. Observe the following code for the same which simply reverses the string stored in the name variable.

name = "Gurmeet Singh"
reversedName = name[::-1]
print(reversedName)

Output.

Reverse String Substring

Similarly, you can try playing with numbers to form different strings or substrings from existing substrings. Explore more about python strings in the official documentation.

I hope you found this tutorial useful. If so, do share it with others who might find it useful as well.

Leave a Reply

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