[英]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. lstrip 或 rstrip 当然不起作用。 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.
我试图查找将替换 function 限制在某些区域的解决方案,但即使我找到了它,我也无法实施它。 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? re.sub(r'\s+(?,[^{]*})', '', list_name)
变成?
See instead going arround re
you can replace uisng string.replace
.请参阅 around
re
你可以替换 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
. Espacillay 当你有多个替换时,你最终会得到更大的
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示例 1 output
word={his or her}whatever
Example 2 output例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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.