How to get Substring in Python

About substring

A substring is a sequence of characters that occur in a string. It is a portion of a string, extracted from the original string based on specific indexes. Substrings are created by extracting a portion of a string using the starting and ending indexes of the desired characters. The extracted characters are then combined to form a new string, which is referred to as the substring. For example, in the string “Hello, World!”, the substring “Hello” can be extracted from the original string by selecting characters 0 to 4.

Get a substring from speciefic section of string

You can get a substring of a string in Python by slicing the string using the index of the characters you want to extract. The syntax is:

Python
string[start:end]

Where ‘start‘ is the index of the first character you want to extract (inclusive) and ‘end‘ is the index of the last character you want to extract (exclusive). For example:

Python
>>> my_string = "Hello, World!"
>>> my_string[7:12]
'World'

If you omit ‘start‘, it is assumed to be 0. If you omit ‘end‘, it is assumed to be the length of the string.

Merge substring

In Python, you can merge substrings using string concatenation or string formatting.

Here’s an example of using string concatenation to merge two substrings:

Python
string1 = "Hello"
string2 = "world"
merged_string = string1 + " " + string2
print(merged_string)  

Output:

Hello world

In this example, the ‘+‘ operator is used to concatenate the two substrings, and the space between the substrings is added as a separate string in between.

Another way to merge substrings is to use string formatting. Here’s an example:

Python
string1 = "Hello"
string2 = "world"
merged_string = "{} {}".format(string1, string2)
print(merged_string)  

Output:

Hello world

In this example, the ‘format()‘ method is used to insert the substrings into the merged string. The curly braces ‘{}‘ serve as placeholders for the substrings, and the ‘format()‘ method inserts them in the order specified.

You can also use f-strings (formatted strings) to merge substrings. Here’s an example:

Python
string1 = "Hello"
string2 = "world"
merged_string = f"{string1} {string2}"
print(merged_string)  

Output:

Hello world

In this example, the ‘f‘ before the string indicates that it is a formatted string. The curly braces ‘{}‘ are used to insert the substrings directly into the merged string.

Share The Tutorial With Your Friends
Twiter
Facebook
LinkedIn
Email
WhatsApp
Skype
Reddit

Check Our Ebook for This Online Course

Advanced topics are covered in this ebook with many practical examples.