Python Forum

Full Version: cut string after tow known chars?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello ,
wanted to know if there is a smart way to do the following:

this is my string
String1 = "data1!data2!data3!data4!data5.......!datax"

I want to save only after data2 :
meaning data3 until the end
String2 = "data3!data4!data5.......!datax"

Up until know I cut after the first "!"
then cut again the second "!"
then I save the new string

but maybe there is a smarter\cleaner way to do this ? ( if something I will need to get the 6th data )?

I found this:
new = string.split("!",2)
which return
['data1', 'data2', 'data3!data4!data5']
****


Found the solution
can remove this post
You almost had it. You just have to reference the third part of the split string by adding [2] to the end of what you have.

new = String1.split("!",2)[2]
Output:
data3!data4!data5.......!datax
def last_element(text, seperator):
    return text.rpartition(seperator)[2]

text = "data3!data4!data5.......!datax"

print(last_element(text, "!"))
print(last_element("test", "!"))
Output:
datax test
Docs for str.rpartition
thank you both!