Home > Enterprise >  How to delete whitespace in only a certain part of the string
How to delete whitespace in only a certain part of the string

Time:03-12

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?

CodePudding user response:

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

CodePudding user response:

How about this...

string = 'abcd <# string that has whitespace> efgh'
s = string.split()
s = ' '.join( (s[0], ''.join(s[1:-1]), s[-1]) )

CodePudding user response:

If <#...> exists consistently, one method to find the string is use regular expressions (regex) to search for that part of the string with the charactersyou want to modify. You then need to strip out the white space.

It takes a bit to get your head around regex, but they can be powerful tool. Regex

  • Related