How to Get a Substring in Python?

Extracting substrings is a common operation in Python programming. Python provides several ways to obtain a substring from a string using slicing and built-in functions.

Using String Slicing

The most common method is to use slicing:

string = "Hello, World!"
substring = string[start:end]

Example:

substring = string[7:12]
print(substring)  # Output: World

Omitting Start or End Index

You can omit the start or end index to slice from the beginning or to the end:

print(string[:5])   # Output: Hello
print(string[7:])   # Output: World!

Using Negative Indices

Negative indices count from the end of the string:

print(string[-6:-1])  # Output: World

Using split() Method

You can split the string and access parts of it:

parts = string.split(", ")
print(parts[1])  # Output: World!

Conclusion

Python’s slicing syntax and string methods make it easy to extract substrings. Mastering these techniques is essential for effective string manipulation.

Leave a Reply

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