如何在python中从字符串中删除额外的空格


{'[\n M a k i n g   c o f f e e   i s   n o t   r e l a t e d   t o   t h e   c o n t e x t   i n f o r m a t i o n   p r o v i d e d .]'}

我需要以下回复:

Making coffee is not related to the context information provided.

我已经试过了:

import re
import json
import string
import re
my_int ={'[\n M a k i n g   c o f f e e   i s   n o t   r e l a t e d   t o   t h e   c o n t e x t   i n f o r m a t i o n   p r o v i d e d .]'}
a=[]
print(type(my_int))
result = re.sub(r'[0-9]', '_', str(my_int))
print(type(result))
print(" ".join(result.split()))
print(result.translate({ord(c): None for c in string.whitespace}))
print(re.sub(r"\s+", "", result), sep='')
print(re.sub(r"^\s+", "", result), sep='')
print(re.sub(r"\s+$", "", result), sep='')
print(re.sub(r"^\s+|\s+$", "", result), sep='')`

为了得到这个结果,我试了所有的方法,但都没有成功。

注意:这里你看到的所有字母都是独立的字符,因此我不能删除它们之间的空格。

非常感谢你的帮助。

多么可怕的输入!

有人为你创建了一个集合,没有任何理由。

他们在里面放了一个元素,这不是一个字符串,而是在[]字符旁边放一个字符串的一种难看的方式。

您可以提取它。对空格的篡改是暂时将双空格转换为其他内容,删除所有其他空格,然后恢复双空格。只要确保您使用的序列,如!DOUBLESPACE!,不会出现在您的字符串中。您可能希望使用您所在地区不使用的国际字符。

my_set ={'[\n M a k i n g   c o f f e e   i s   n o t   r e l a t e d   t o   t h e   c o n t e x t   i n f o r m a t i o n   p r o v i d e d .]'}
my_string = list(my_set)[0].replace("[","").replace("]","").replace("\n","").replace("  ","!DOUBLESPACE!").replace(" ","").replace("!DOUBLESPACE!"," ")
print(my_string)

不需要import

结果:

Making coffee is not related to the context information provided.

结果类型

您肯定不想要set结果。有人给了你一个集合作为输入。

上面代码的结果my_string只是一个字符串。请确保在后续处理中使用该集合,而不是集合。

尝试:

import re
my_int = {'[\n M a k i n g   c o f f e e   i s   n o t   r e l a t e d   t o   t h e   c o n t e x t   i n f o r m a t i o n   p r o v i d e d .]'}
for s in my_int:
s = re.sub(r'\.', '', s)
s = re.sub(r's(?=S)|(?<=S)s', '', s)
print(s)

打印:

Making coffee is not related to the context information provided.

最新更新