Python Forum

Full Version: How to split string after delimiter
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
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