Python Forum
How to split string after delimiter
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to split string after delimiter
#1
Hi,
I have a string as below, I want to split after each "html" and extract the first string after split.
I use below code, but I can be able to split after the delimiter.

a='JKl:TOGGLE:HJAK.html:Tiger:HJA.html'
b=a.split('html')[0]
My desired output is :JKl:TOGGLE:HJAK.htm
Reply
#2
I would just add the htm then after splitting as str.split removes the delimiter. You need to add a portion of it back. There are a number of ways to do that
>>> [f'{e}html' for e in s.split('html') if e][0]
'JKl:TOGGLE:HJAK.html'
(Sep-11-2019, 10:58 AM)SriRajesh Wrote: :JKl:TOGGLE:HJAK.htm
Where is the first colon coming from as that is not in the original string?
If you want to add a colon:
>>> [f':{e}html' for e in s.split('html') if e][0]
':JKl:TOGGLE:HJAK.html'
or remove l from html
>>> [f':{e}html' for e in s.split('html') if e][0][:-1]
':JKl:TOGGLE:HJAK.htm'
NOTE: my response is using f-strings from python3.6
Recommended Tutorials:
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  python Read each xlsx file and write it into csv with pipe delimiter mg24 4 1,408 Nov-09-2023, 10:56 AM
Last Post: mg24
  doing string split with 2 or more split characters Skaperen 22 2,470 Aug-13-2023, 01:57 AM
Last Post: Skaperen
Sad How to split a String from Text Input into 40 char chunks? lastyle 7 1,120 Aug-01-2023, 09:36 AM
Last Post: Pedroski55
  Context-sensitive delimiter ZZTurn 9 1,442 May-16-2023, 07:31 AM
Last Post: Gribouillis
  [split] Parse Nested JSON String in Python mmm07 4 1,509 Mar-28-2023, 06:07 PM
Last Post: snippsat
  Read csv file with inconsistent delimiter gracenz 2 1,185 Mar-27-2023, 08:59 PM
Last Post: deanhystad
  Split string using variable found in a list japo85 2 1,293 Jul-11-2022, 08:52 AM
Last Post: japo85
  Delimiter issue with a CSV file jehoshua 1 1,273 Apr-19-2022, 01:28 AM
Last Post: jehoshua
  Split string knob 2 1,861 Nov-19-2021, 10:27 AM
Last Post: ghoul
  How to create new line '/n' at each delimiter in a string? MikeAW2010 3 2,810 Dec-15-2020, 05:21 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

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