【问题标题】:Remove whitespaces that are not inside quotes [duplicate]删除不在引号内的空格[重复]
【发布时间】:2013-01-27 15:00:48
【问题描述】:

可能重复:
Python Regular expression must strip whitespace except between quotes

我需要删除文件中不在单引号或双引号内(即不在字符串中)的所有空格。

我找到了这个解决方案 Python Regular expression must strip whitespace except between quotes

但这仅适用于双引号

【问题讨论】:

  • 你试过把它改成单引号吗?
  • 单引号嵌套在双引号中会怎样?
  • 当您询问有关您编写的代码的问题时,堆栈溢出效果最好,而不是仅仅要求某人为您编写代码。
  • 如果单引号嵌套在双引号中或双引号嵌套在单引号中,则不得删除空格(在整个字符串中)

标签: python whitespace


【解决方案1】:

去掉引号外的空格:

import re

parts = re.split(r"""("[^"]*"|'[^']*')""", text)
parts[::2] = map(lambda s: "".join(s.split()), parts[::2]) # outside quotes
print("".join(parts))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-26
    • 2015-10-08
    • 1970-01-01
    • 2022-01-13
    • 2021-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多