Python Forum
cut string after tow known chars?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
cut string after tow known chars?
#1
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
Reply
#2
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
Reply
#3
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
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#4
thank you both!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Can't stop keyboard listener to grab chars typed inside CTk window Valjean 9 1,376 Sep-25-2023, 08:07 PM
Last Post: deanhystad
  json.dumps save some unicode chars as code, not char buran 1 2,928 Aug-02-2018, 04:02 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020