Just use the split function. It returns a list, so you can keep the first element:

>>> s1.split(':')
['Username', ' How are you today?']
>>> s1.split(':')[0]
'Username'
Answer from fredtantini on Stack Overflow
๐ŸŒ
Medium
medium.com โ€บ @Alexander_H โ€บ removing-characters-before-after-and-in-the-middle-of-strings-fb4930cce76a
Removing characters before, after, and in the middle of strings | by This Time Is Different | Medium
October 30, 2017 - When working with real-world datasets ... it was given and deletes that character..lstrip() #strips everything before and including the character or set of characters you say....
๐ŸŒ
EyeHunts
tutorial.eyehunts.com โ€บ home โ€บ python cut string before character | example code
Python cut string before character | Example code - EyeHunts
October 28, 2021 - Simple example code cut all chars of a string before a โ€œandโ€ in python. Just use the split function. It returns a list, and keep the first element: s = "Python and data science" res = s.split("and")[0] print(res) ...
Discussions

python - how to get the last part of a string before a certain character? - Stack Overflow
I am trying to print the last part of a string before a certain character. I'm not quite sure whether to use the string .split() method or string slicing or maybe something else. Here is some More on stackoverflow.com
๐ŸŒ stackoverflow.com
Python - How to cut a string in Python? - Stack Overflow
re.split(r'&.*', s) splits the string at the first & and everything after it. It is particulary useful if your separator is more complex than a single character. More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to remove part of string after certain character in python?

There are a few ways. Here are a few off the top of my head:

>>> s = "abcd//efgh"

>>> s.find("/")
4
>>> s[:s.find("/")]
'abcd'

>>> s.split("/")
['abcd', '', 'efgh']
>>> s.split("/", maxsplit=1)
['abcd', '/efgh']
>>> s.split("/", maxsplit=1)[0]
'abcd'

>>> import re
>>> re.sub("/.*$", "", s)
'abcd'

The last is overkill here and I wouldn't use it, but regexs are often appropriate for doing search & replace operations. Either of the first two would work pretty well. The first depends on the search string appearing though. Otherwise, s.find will return -1 and then s[:-1] will lop off the last character:

>>> s = "abcdef"
>>> s[:s.find("/")]
'abcde'
More on reddit.com
๐ŸŒ r/AskProgramming
4
5
July 2, 2017
I am new to python how to remove the first character(letter) from a word in python?
Strings can be indexed/sliced with the variable[start:end:step] construct. It starts at zero, so a simple way of removing the leading character is to just slice the string starting from 1. This can be used to assign the slice to a new variable or to print directly, in which case you simply encase the variable and the slice in print's parentheses. There's also the slice() built-in. More on reddit.com
๐ŸŒ r/learnprogramming
5
0
February 2, 2021
๐ŸŒ
Kite
kite.com โ€บ python โ€บ answers โ€บ how-to-get-the-part-of-a-string-before-a-specific-character-in-python
Kite is saying farewell - Code Faster with Kite
November 20, 2022 - P.S. Most of our code has been open sourced on Github here. It includes our data-driven Python type inference engine, Python public-package analyzer, desktop software, editor integrations, Github crawler and analyzer, and much more.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-string-till-substring
Python - String till Substring - GeeksforGeeks
July 12, 2025 - The split() method is a simple and efficient way to extract the part of a string before a specific substring. By splitting the string at the substring and taking the first part, we can achieve the desired result.
๐ŸŒ
thisPointer
thispointer.com โ€บ home โ€บ python โ€บ remove string before a specific character in python
Remove String before a Specific Character in Python - thisPointer
May 4, 2022 - It deleted everything before the character โ€˜-โ€˜ from the string. In Python, the string class provides a function partition(sep). It accepts a separator as an argument and splits the string into three parts based on the given separator.
๐ŸŒ
Bobby Hadz
bobbyhadz.com โ€บ blog โ€บ python-remove-everything-after-character
Remove everything Before or After a Character in Python | bobbyhadz
April 9, 2024 - Copied!my_str = 'example.com/articles/python' result = ''.join(my_str.rpartition('/')[1:]) print(result) # ๐Ÿ‘‰๏ธ '/python' The str.join() method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable. The string the method is called on is used as the separator between the elements. You can learn more about the related topics by checking out the following tutorials: Remove all Non-Numeric characters from a String in Python
Find elsewhere
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python
Remove a Substring from a String in Python | note.nkmk.me
April 23, 2025 - Use strip() to remove specified leading and trailing characters from a string. Built-in Types - str.strip() โ€” Python 3.13.3 documentation
๐ŸŒ
Linux Hint
linuxhint.com โ€บ substring-after-character-python
Python Substring After Character โ€“ Linux Hint
The element before the supplied string is included in the first element. On the other hand, the specified string is contained in the second element. Call the โ€œpartition()โ€ method with a string value as an argument and specify the desired element index. Then, store it in the declared โ€œresult_stringโ€ variable: ... Another efficient way of substring after the character in Python...
๐ŸŒ
w3resource
w3resource.com โ€บ python-exercises โ€บ string โ€บ python-data-type-string-exercise-19.php
Python: Get the last part of a string before a specified character - w3resource
June 12, 2025 - Then, print the result. ...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....
๐ŸŒ
Python Central
pythoncentral.io โ€บ cutting-and-slicing-strings-in-python
Cutting and slicing strings in Python - Python Central
September 6, 2023 - An overview on all of the ways you can cut and slice strings with the Python programming language. With lots of examples/code samples!
Top answer
1 of 2
135

You are looking for str.rsplit(), with a limit:

print x.rsplit('-', 1)[0]

.rsplit() searches for the splitting string from the end of input string, and the second argument limits how many times it'll split to just once.

Another option is to use str.rpartition(), which will only ever split just once:

print x.rpartition('-')[0]

For splitting just once, str.rpartition() is the faster method as well; if you need to split more than once you can only use str.rsplit().

Demo:

>>> x = 'http://test.com/lalala-134'
>>> print x.rsplit('-', 1)[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rsplit('-', 1)[0]
'something-with-a-lot-of'

and the same with str.rpartition()

>>> print x.rpartition('-')[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rpartition('-')[0]
'something-with-a-lot-of'
2 of 2
6

Difference between split and partition is split returns the list without delimiter and will split where ever it gets delimiter in string i.e.

x = 'http://test.com/lalala-134-431'

a,b,c = x.split(-)
print(a)
"http://test.com/lalala"
print(b)
"134"
print(c)
"431"

and partition will divide the string with only first delimiter and will only return 3 values in list

x = 'http://test.com/lalala-134-431'
a,b,c = x.partition('-')
print(a)
"http://test.com/lalala"
print(b)
"-"
print(c)
"134-431"

so as you want last value you can use rpartition it works in same way but it will find delimiter from end of string

x = 'http://test.com/lalala-134-431'
a,b,c = x.rpartition('-')
print(a)
"http://test.com/lalala-134"
print(b)
"-"
print(c)
"431"
๐ŸŒ
Finxter
blog.finxter.com โ€บ home โ€บ learn python blog โ€บ python | split string until character/substring
Python | Split String until Character/Substring - Be on the Right Side of Change
December 15, 2022 - In the above solutions, it finds and groups all the characters until โ€œBoyโ€ in the first case and โ€œ/โ€ in the second case. ... The partition() method searches for a separator substring and returns a tuple with three strings: (1) everything before the separator, (2) the separator itself, and (3) everything after it.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-remove-after-substring-in-string
Python - Remove after substring in String - GeeksforGeeks
July 15, 2025 - We can use the split() method to split the string at the desired substring and keep only the part before it.
Top answer
1 of 7
62

Well, to answer the immediate question:

>>> s = "http://www.domain.com/?s=some&two=20"

The rfind method returns the index of right-most substring:

>>> s.rfind("&")
29

You can take all elements up to a given index with the slicing operator:

>>> "foobar"[:4]
'foob'

Putting the two together:

>>> s[:s.rfind("&")]
'http://www.domain.com/?s=some'

If you are dealing with URLs in particular, you might want to use built-in libraries that deal with URLs. If, for example, you wanted to remove two from the above query string:

First, parse the URL as a whole:

>>> import urlparse, urllib
>>> parse_result = urlparse.urlsplit("http://www.domain.com/?s=some&two=20")
>>> parse_result
SplitResult(scheme='http', netloc='www.domain.com', path='/', query='s=some&two=20', fragment='')

Take out just the query string:

>>> query_s = parse_result.query
>>> query_s
's=some&two=20'

Turn it into a dict:

>>> query_d = urlparse.parse_qs(parse_result.query)
>>> query_d
{'s': ['some'], 'two': ['20']}
>>> query_d['s']
['some']
>>> query_d['two']
['20']

Remove the 'two' key from the dict:

>>> del query_d['two']
>>> query_d
{'s': ['some']}

Put it back into a query string:

>>> new_query_s = urllib.urlencode(query_d, True)
>>> new_query_s
's=some'

And now stitch the URL back together:

>>> result = urlparse.urlunsplit((
    parse_result.scheme, parse_result.netloc,
    parse_result.path, new_query_s, parse_result.fragment))
>>> result
'http://www.domain.com/?s=some'

The benefit of this is that you have more control over the URL. Like, if you always wanted to remove the two argument, even if it was put earlier in the query string ("two=20&s=some"), this would still do the right thing. It might be overkill depending on what you want to do.

2 of 7
52

You need to split the string:

>>> s = 'http://www.domain.com/?s=some&two=20'
>>> s.split('&')
['http://www.domain.com/?s=some', 'two=20']

That will return a list as you can see so you can do:

>>> s2 = s.split('&')[0]
>>> print s2
http://www.domain.com/?s=some
๐ŸŒ
Finxter
blog.finxter.com โ€บ home โ€บ learn python blog โ€บ python | split string before delimiter
Python | Split String Before Delimiter - Be on the Right Side of Change
December 15, 2022 - Approach: Therefore, you can use the takewhile method of the itertools module and feed in a lambda function that considers and groups all characters in the given string until the occurrence of the delimiter โ€œ-โ€œ. Once it reaches the delimiter, the predicate becomes false; hence the iteration ...
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ article โ€บ python-prefix-extraction-before-specific-character
Python - Prefix extraction before specific character
September 1, 2023 - Use split()[0] for simple prefix extraction. Use find() with slicing when you need more control over the process. The split(delimiter, 1) approach is best when dealing with strings containing multiple instances of the same delimiter.
๐ŸŒ
Esri Community
community.esri.com โ€บ t5 โ€บ python-questions โ€บ remove-all-characters-before-a-certain-character โ€บ td-p โ€บ 197897
Remove all characters before a certain character with Python using Field Calculator
June 2, 2022 - I was looking for that too and I found it on another thread (Removing text after comma). I was trying to remove characters after a &. I'm not sure the link will link to the thread. ... my_string = '<img src="X:\UB_Routing\images\ServiceOrders\150 E MAIN ST.png"><br>150 E MAIN ST' print my_string.split('<br>')[1] 150 E MAIN ST โ€โ€โ€โ€
๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ python-trim
How to Trim a String in Python: Three Different Methods | DataCamp
February 16, 2025 - Python provides built-in methods to trim strings, making it straightforward to clean and preprocess textual data. These methods include ยท .strip(): Removes leading and trailing characters (whitespace by default).