In this article let's learn a Python program to get the part of a string before a given character. The input to the Python program is text containing a string and a character.
The Python program should print the part of a string ignoring the last part of a string.
Write a Python Program to Get The Last Part of a String Before a Specified Character
Let's take the variables text and char, ask the user for interesting and a character using the input function call and store them into the variables respectively.
Take another variable named as pointer and initialize it to none, this will point to the last appearing character of a string.
text = input("Enter a String : ")
char = input("Enter a Char : ")
pointer = None
Use the for loop to iterate all the letters present in the string, also get the index by using the enumerate function call. use the if statement to check if letter is equals to the given character and set the pointer accordingly to the index
for index, letter in enumerate(text):
if letter == char:
pointer = index
Once the for loop is completed the pointer will point to the last appearing character of a given string, check if the pointer is not None then use the string slicing method and print the string before the character appears as shown below using the print function call.
if pointer is not None:
print("The Last Part of String is : ", text[:pointer])
else:
print("The Given Character is not present in String !!!")
Complete Python Program
===================================
text = input("Enter a String : ")
char = input("Enter a Char : ")
pointer = None
for index, letter in enumerate(text):
if letter == char:
pointer = index
if pointer is not None:
print("The Last Part of String is : ", text[:pointer])
else:
print("The Given Character is not present in String !!!")
Output
===================
Enter a String : hello python
Enter a Char : h
String Before a Specified Character : hello pyt
Output
===================
Enter a String : Write a Python Program to Get The Last Part of a String Before a Specified Character
Enter a Char : a
String Before a Specified Character : Write a Python Program to Get The Last Part of a String Before a Specified Char
Conclusion
=====================
Execute the above code by providing random string and character as an input to the Python program, note down the result.
Comment it down below if you have any suggestions to improve the above python program.
0 Comments