Python – Get substring before specific character

Python – Get substring before specific character

To get the substring before a specific character in a string in Python, you can first find the index of the specified character using string find(), and then slice the string from start up to found index of the specified character.

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

1. Get substring before 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 starting of the string up to the character ch.

x[:ch_index]

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

Python Program

# Input string
x = "Hello World!"

# Specific character
ch = "r"

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

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

# Print the result
print(substring)
Run Code Copy

Output

Hello Wo

Related Tutorials

Summary

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

Related Tutorials

Code copied to clipboard successfully 👍