简体   繁体   中英

How to remove whitespaces in a string except from between certain elements

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?

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

You can use by replace

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

string = 'hell o whatever'
print(remove(string)) // Output: hellowhatever

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM