w3resource

Python: Get the last part of a string before a specified character

Python String: Exercise-19 with Solution

Write a Python program to get the last part of a string before a specified character.

Python String Exercises: Get the last part of a string before a specified character

Sample Solution:

Python Code:

# Define a variable 'str1' and assign it the value of the provided string.
str1 = 'https://www.w3resource.com/python-exercises/string'

# Use the rsplit() method with '/' as the separator to split the string from the right,
# and [0] to get the part before the last '/' character. Then, print the result.
print(str1.rsplit('/', 1)[0])  # Output: 'https://www.w3resource.com/python-exercises'

# Use the rsplit() method with '-' as the separator to split the string from the right,
# and [0] to get the part before the last '-' character. Then, print the result.
print(str1.rsplit('-', 1)[0])  # Output: 'https://www.w3resource.com/python' 

Sample Output:

https://www.w3resource.com/python-exercises                                                                    
https://www.w3resource.com/python               

Flowchart:

Flowchart: Get the last part of a string before a specified character

Python Code Editor:

Previous: Write a Python function to get a string made of its first three characters of a specified string. If the length of the string is less than 3 then return the original string.
Next: Write a Python function to reverse a string if it's length is a multiple of 4.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.