小编Dee*_*dav的帖子

Python:如果以反斜杠分隔,则加入连续的行并删除反斜杠

我有一个包含 shell 命令的文件。每个命令可以分成多行(在末尾使用反斜杠):
例如

  cmd1 -opt1 \  
    -opt2 val2  \  
    -opt3 val3 val4
Run Code Online (Sandbox Code Playgroud)

如果最后以反斜杠分隔,我想加入连续的行。我也想在加入后删除反斜杠。

问题类似于:
Input:
['abc', 'def \\', 'ghi \\', 'jkl' , 'yyy \\', 'zzz']
output:
['abc', 'def ghi jkl ', 'yyy zzz']

是循环遍历列表唯一的解决方案吗?

with open("cmd", "r") as fp:
    cmd = ""
    cont = False
    list = []
    for line in fp:
        line = line.rstrip("\n")
        if line.endswith('\\'):
            line = line[:-1]
            if cont:
                cmd = cmd + line
                continue
            if cmd:
                list.append(cmd)
            cmd = line
            cont = True
        else:
            if …
Run Code Online (Sandbox Code Playgroud)

python

4
推荐指数
1
解决办法
893
查看次数

在花括号内用空格保留字符串

str = "cmd -opt1 { a b c  d e f g h } -opt2" 
Run Code Online (Sandbox Code Playgroud)

我想要这样的输出:

[ 'cmd', '-opt1', '{ a b c  d e f g h }', '-opt2' ]  
Run Code Online (Sandbox Code Playgroud)

python regex

3
推荐指数
1
解决办法
949
查看次数

标签 统计

python ×2

regex ×1