How To Get Substring Of A String In Python?

Generate Substrings Python

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

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 logics. The following lines of code will help you form a string by choosing the alternate string characters.

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 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.

Output.

Reverse String Substring

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.

Related Articles.

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.

Subscribe To WTMatter!

Receive updates of our latest articles via email. Enter your email address below to get started.

Leave a Reply

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