[Python] Parse a string, leaving special characters at the end of the word [closed]

Discussão em 'Python' iniciado por Stack, Março 27, 2025.

  1. Stack

    Stack Membro Participativo

    My task:

    I would like to correctly parse the string by any special characters and spaces. In my further examples, for simplicity, the special characters will be a colon :)) and a period (.) , but in general I can come across any special characters.

    Initial data:

    initial_string_1 = "Date: 01/12/2024"

    initial_string_2 = "Batch No.159"

    initial_string_3 = "TRAILER REF. NO.: ADB456RED"

    Please note that in initial_string_2 no space between the special character and the number.

    Desire result:

    I would like to separate words and meanings into lines

    desire_list_1 = ['Date:', '01/12/2024']

    desire_list_2 = ['Batch No.', '159']

    desire_list_3 = ['TRAILER REF. NO.:', 'ADB456RED']

    What I have at the moment:

    I made a regular expression

    re.split(r'(?<=[:.])', initial_string)


    and I get the following result

    result_list_1 = ['Date:', ' 01/12/2024']

    result_list_2 = ['Batch No.', '159']

    result_list_3 = ['TRAILER REF.', ' NO.', ':', ' ADB456RED']

    However, as you can see, the actual results are far from expected:

    1. In the first and third cases, spaces remain at the beginning of the line
    2. Second case is correct
    3. In the third case I would like it to 'TRAILER REF. NO.:' be one line

    Continue reading...

Compartilhe esta Página