This is a quick tutorial on how you can generate different types of substrings from an existing string in python using string slicing method.
Getting Different Substrings Of A String In Python
Consider the following code. I’ve stored my name into 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:]
#Only Get First 3 Characters
subString2 = fullString[:3]
#Remove Last 3 Characters
subString3 = fullString[:-3]
#Only Get Last 3 Characters
subString4 = fullString[-3:]
#Slice First 3 and Last 3 Characters
subString5 = fullString[3:-3]
The output of the above code is shown in the following screenshot.
Alternate Characters Substrings
You can also use the same slicing concept in python to generate substrings by forming a lot more logics. 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
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 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]
Similarly, you can try by playing with numbers to form different strings or substrings from existing substrings. Explore more about python string in the official documentation.
- Python New Line – The New Line Character in Python
- How to Split String in Python?
- Octal To Decimal Conversion In Python
- Find Size of A List In Python
- Python For Loop – Different Types of For Loops With Examples
I hope you found this tutorial useful. If so, do share it with others who might find it useful as well. Also, don’t forget to subscribe to WTMatter.com and feel free to ask any kind of questions related to this article in the comments section given below.