Python: str split on repeated instances in single string
Question:
How can I split and remove repeated patterns from a string, such as?
# sample
s1 = '-c /home/test/pipeline/pipelines/myspace4/.cache/sometexthere/more --log /home/test1/pipeline2/pipelines1/myspace1/.cache/sometexthere/more --arg /home/test4/pipeline3/pipelines3/myspace3/.cache/sometexthere/more --newarg etc.'
# expected
expected = '-c sometexthere/more --log sometexthere/more --arg sometexthere/more --newarg etc.'
# attempt only yields last value rather than all
''.join([ s for s in s1.split('/.cache/')[-1] ])
Answers:
First split your string around spaces, so all the relevant parts will be split afterwards:
s2 = ' '.join([part.split('/.cache/')[-1] for part in s1.split()])
Output:
'-c sometexthere/more --log sometexthere/more --arg sometexthere/more --newarg etc.'
How can I split and remove repeated patterns from a string, such as?
# sample
s1 = '-c /home/test/pipeline/pipelines/myspace4/.cache/sometexthere/more --log /home/test1/pipeline2/pipelines1/myspace1/.cache/sometexthere/more --arg /home/test4/pipeline3/pipelines3/myspace3/.cache/sometexthere/more --newarg etc.'
# expected
expected = '-c sometexthere/more --log sometexthere/more --arg sometexthere/more --newarg etc.'
# attempt only yields last value rather than all
''.join([ s for s in s1.split('/.cache/')[-1] ])
First split your string around spaces, so all the relevant parts will be split afterwards:
s2 = ' '.join([part.split('/.cache/')[-1] for part in s1.split()])
Output:
'-c sometexthere/more --log sometexthere/more --arg sometexthere/more --newarg etc.'