Pythonic方式重写以下C++字符串处理代码

Che*_*eng 2 c++ python

上一篇,我有一个C++字符串处理代码,能够做到这一点.

input -> Hello 12
output-> Hello

input -> Hello 12 World
output-> Hello World

input -> Hello12 World
output-> Hello World

input -> Hello12World
output-> HelloWorld
Run Code Online (Sandbox Code Playgroud)

以下是C++代码.

std::string Utils::toStringWithoutNumerical(const std::string& str) {
    std::string result;

    bool alreadyAppendSpace = false;
    for (int i = 0, length = str.length(); i < length; i++) {
        const char c = str.at(i);
        if (isdigit(c)) {
            continue;
        }
        if (isspace(c)) {
            if (false == alreadyAppendSpace) {
                result.append(1, c);
                alreadyAppendSpace = true;
            }
            continue;
        }
        result.append(1, c);
        alreadyAppendSpace = false;
    }

    return trim(result);
}
Run Code Online (Sandbox Code Playgroud)

我可以用Python知道,实现这种功能的Pythonic方法是什么?正则表达能够实现吗?

谢谢.

Sve*_*ach 7

编辑:这比以前的版本更准确地再现了C++代码.

s = re.sub(r"\d+", "", s)
s = re.sub(r"(\s)\s*", "\1", s)
Run Code Online (Sandbox Code Playgroud)

特别是,如果几个空格中的第一个空格是一个选项卡,它将保留选项卡.

进一步编辑:无论如何要用空格替换,这有效:

s = re.sub(r"\d+", "", s)
s = re.sub(r"\s+", " ", s)
Run Code Online (Sandbox Code Playgroud)


Mar*_*som 5

Python有许多内置函数,当它们一起使用时可以非常强大.

def RemoveNumeric(str):
    return ' '.join(str.translate(None, '0123456789').split())

>>> RemoveNumeric('Hello 12')
'Hello'
>>> RemoveNumeric('Hello 12 World')
'Hello World'
>>> RemoveNumeric('Hello12 World')
'Hello World'
>>> RemoveNumeric('Hello12World')
'HelloWorld'
Run Code Online (Sandbox Code Playgroud)