[SOLVED] How to delete whitespace in only a certain part of the string

Issue

So let’s say I have this string like

string = 'abcd <# string that has whitespace> efgh'

And I want to delete all the white space inside this <#...> And not affect anything outside <#...>

But the characters outside <#...> can change too so the <#...> is not going to be in a fixed position.

How should I do this?

Solution

This is not a complicated operation. You just do it like you would as a human being. Find the two delimiters, keep the part before the first one, remove space from the middle, keep the rest.

string = 'abcd <# string that has whitespace> efgh'

i1 = string.find('<#')
i2 = string.find('>')

res = string[:i1] + string[i1:i2].replace(' ','') + string[i2:]
print(res)

Output:

abcd <#stringthathaswhitespace> efgh

Answered By – Tim Roberts

Answer Checked By – Clifford M. (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *