python字符串操作和处理

标签 python parsing

我有许多需要处理的代码,这些代码以多种不同的格式出现,我需要首先对其进行操作以使它们具有正确的格式:

代码示例:

ABC1.12 - correct format
ABC 1.22 - space between letters and numbers
ABC1.12/13 - 2 codes joined together and leading 1. missing from 13, should be ABC1.12 and ABC1.13 
ABC 1.12 / 1.13 - codes joined together and spaces

我知道如何删除空格,但不确定如何处理已拆分的代码。我知道我可以使用 split 函数创建 2 个代码,但不确定如何将字母(和第一个数字部分)附加到第二个代码。这是上面列表中的第 3 个和第 4 个示例。

到目前为止我有什么

    val = # code
    retList = [val]
    if "/" in val:
        (code1, code2) = session_codes = val.split("/", 1)

        (inital_letters, numbers) = code1.split(".", 1)
        if initial_letters not in code2:
            code2 = initial_letters + '.' + code2

        # reset list so that it returns both values 
        retList = [code1, code2]

这不会真正处理 4 的拆分,因为 code2 变为 ABC1.1.13

最佳答案

您可以为此目的使用正则表达式

可能的实现如下

>>> def foo(st):
    parts=st.replace(' ','').split("/")
    parts=list(re.findall("^([A-Za-z]+)(.*)$",parts[0])[0])+parts[1:]
    parts=parts[0:1]+[x.split('.') for x in parts[1:]]
    parts=parts[0:1]+['.'.join(x) if len(x) > 1 else '.'.join([parts[1][0],x[0]]) for x in parts[1:]]
    return [parts[0]+p for p in parts[1:]]

>>> foo('ABC1.12')
['ABC1.12']
>>> foo('ABC 1.22')
['ABC1.22']
>>> foo('ABC1.12/13')
['ABC1.12', 'ABC1.13']
>>> foo('ABC 1.12 / 1.13')
['ABC1.12', 'ABC1.13']
>>> 

关于python字符串操作和处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9872592/

相关文章:

python - 在 pyparsing 中使用 QuotedString

python - 为什么在我拆分一些 HTML 源代码时会出现 b'(有时是 b' ')[Python]

parsing - 如何从字符串中手动解析 float

c# - 将C#中的长字符串发送到Python的最快方法

python - Nose 、unittest.TestCase 和元类 : auto-generated test_* methods not discovered

python - Google App-Engine 为自己的 Python 应用程序运行 setup.py install

Python获取所有的CSS链接

php - 提高 php-cli 中大型 csv 文件解析的性能

python - 使用多个 AND 语句的 Pandas read_sql_query

python 扭曲 : Create SSLv2 context