python - 在python中解析字符串

标签 python string parsing

所以我的问题是,我有一个如下所示的文件:

[SHIFT]this isrd[BACKSPACE][BACKSPACE] an example file[SHIFT]1

这当然会转化为

' This is an example file!'

我正在寻找一种将原始内容解析为最终内容的方法,这样 [BACKSPACE] 将删除最后一个字符(包括空格),多个退格将删除多个字符。 [SHIFT] 对我来说并不那么重要。感谢所有的帮助!

最佳答案

这是一种方法,但感觉很老套。可能有更好的方法。

def process_backspaces(input, token='[BACKSPACE]'):
    """Delete character before an occurence of "token" in a string."""
    output = ''
    for item in (input+' ').split(token):
        output += item
        output = output[:-1]
    return output

def process_shifts(input, token='[SHIFT]'):
    """Replace characters after an occurence of "token" with their uppecase 
    equivalent. (Doesn't turn "1" into "!" or "2" into "@", however!)."""
    output = ''
    for item in (' '+input).split(token):
        output += item[0].upper() + item[1:]
    return output

test_string = '[SHIFT]this isrd[BACKSPACE][BACKSPACE] an example file[SHIFT]1'
print process_backspaces(process_shifts(test_string))

关于python - 在python中解析字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4882249/

相关文章:

python - 如何在python中生成给定顶点数的所有3个正则图

python - 使用 Python 将文件夹上传到 Google Cloud Storage?

c - 循环无法正常工作(字符串)

c# - Linq - 用引号聚合字符串

ios - 自定义单元格图像作为 Swift 中的附件类型

C : Parsing options the right way

python - 如何在独立的环境中嵌入 Bokeh 服务器

python Pandas : Sorting Columns

excel - 使用替换功能将一个字符替换为两个

javascript - 如何使用 native Angular 代码解析外部链接 url?