【问题标题】:Preserve "\t", "\n", "\r" when spliting a string using shlex in python在 python 中使用 shlex 拆分字符串时保留“\t”、“\n”、“\r”
【发布时间】:2020-04-20 11:32:20
【问题描述】:

我正在尝试使用 shlex 拆分字符串,但我想保留(字面意思)“\t”、“\n”、“\r”。

例子:

text = "a=\t\n\r\example c=d"
sp_text = shlex.split(text)
print(sp_text)

['a=', 'example', 'c=d']

但我想打印这个:

['a=\t\n\r\example', 'c=d']

我可以使用 shlex 做到这一点吗?

/安杰洛斯

【问题讨论】:

    标签: python split shlex


    【解决方案1】:

    您可以执行以下操作:

    import shlex
    
    text = "a=\t\n\r\example c=d"
    
    sh = shlex.shlex(text)
    sh.whitespace = ' '
    sh.whitespace_split = True
    
    sp_text = list(sh)
    print(sp_text)
    

    输出

    ['a=\t\n\r\\example', 'c=d']
    

    请注意,上面的示例仅使用单个空格进行拆分,示例的想法是说明如何操作 shlex 空格。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多