0

I have a string similar to (the below one is simplified):

"  word=       {his or her}      whatever  "

I want to delete every whitespace except between {}, so that my modified string will be:

"word={his or her}whatever"

lstrip or rstrip doesn't work of course. If I delete all whitespaces the whitespaces between {} are deleted as well. I tried to look up solutions for limiting the replace function to certain areas but even if I found out it I haven't been able to implement it. There are some stuff with regex (I am not sure if they are relevant here) but I haven't been able to understand them.

EDIT: If I wanted to except the area between, say {} and "", that is:

if I wanted to turn this string:

"  word=       {his or her} and "his or her"      whatever  "

into this:

"word={his or her}and"his or her"whatever"

What would I change

re.sub(r'\s+(?![^{]*})', '', list_name) into?

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • This is typically adressed by using regular expressions. See https://stackoverflow.com/questions/66429357/regex-to-ignore-data-between-brackets – Gaël James Dec 04 '22 at 12:56

2 Answers2

1

See instead going arround re you can replace uisng string.replace. Which will be much more easier and less complex when you playing around strings. Espacillay when you have multiple substitutions you end up bigger regex.

st ="  word=       {his or her}      whatever  "
st2="""  word=       {his or her} and "his or her"      whatever  """

new = " ".join(st2.split())
new = new.replace("= ", "=").replace("} ", "}").replace('" ' , '"').replace(' "' , '"')
print(new)

Some outputs

Example 1 output

word={his or her}whatever

Example 2 output

word={his or her}and"his or her"whatever
-2

You can use by replace

def remove(string):
    return string.replace(" ", "")

string = 'hell o whatever'
print(remove(string)) // Output: hellowhatever
Mihir B
  • 99
  • 11