0

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?

1
  • 2
    Welcome to Stackoverflow! Your question needs more details: a) input samples b) expected outputs for these inputs c) what code have you already tried as solution. That way we can help you better! Commented Mar 12, 2022 at 4:40

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

Comments

1

How about this...

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.