Python - Get substring after specific character


Python - Get substring after specific character

To get the substring after a specific character in a string in Python, you can first find the index of the specified character, and then slice the string from index+1 to the end of the string.

In this tutorial, you will learn how to get the substring after a specific character in a string in Python, using string find() method and string slicing, with examples.

1. Get substring after specific character using string find() method and string slicing in Python

If x is the given string, then use the following expression to get the index of specified character ch.

x.find(ch)

If the returned value ch_index is not -1, i.e., the specified character ch is present in the string x, then use the following expression to slice the string from the character after ch till the end of the string x.

x[ch_index+1:]

In the following program, we take a string value in variable x, character value in ch, and find the substring after the character ch in string x.

Python Program

# Input string
x = "Hello World!"

# Specific character
ch = "W"

# Find the index of the character
ch_index = x.find(ch)

if ch_index != -1:
    # Get the substring after the character
    substring = x[ch_index + 1:]
else:
    # Character not found, handle it accordingly
    substring = ""

# Print the result
print(substring)

Output

orld!

Related Tutorials

Summary

In this tutorial, we learned how to get the substring after a specific character in a string in Python using string find() method and string slicing, with the help of examples.