使用re.sub,您将需要多个正则表达式模式来完成此操作。以下是每一步应用于您的字符串的步骤和转换。
import re
s = '[ A A A A A B B B B B B B B A A A A A ]'
# Using a lookbehind, we remove spaces preceeded by a [
s = re.sub('(?<=\[) +', '', s)
# s: '[A A A A A B B B B B B B B A A A A A ]'
# Using a lookahead, we remove spaces followed by a ]
s = re.sub(' +(?=\])', '', s)
# s: '[A A A A A B B B B B B B B A A A A A]'
# Using a lookaround, we remove space not followed or preceeded by another space
s = re.sub('(?<! ) (?! )', '', s)
# s: '[AAAAA BBBBBBBB AAAAA]'
# Finally, we use str.replace to cut out half of the spaces
s = s.replace(' ', ' ')
print(s) # '[AAAAA BBBBBBBB AAAAA]'
上述步骤可以通过使用正则表达式联合并链接re.sub和str.replace操作来合并。
s = re.sub('((?<=\[) +)|( +(?=\]))|((?<! ) (?! ))', '', s).replace(' ', ' ')