Bonjour,
le code ci-dessous me permet d'élargir les possibilités de la méthode split. L'emploi de la récursivité rend les choses immédiates à programmer.
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#!/usr/bin/env python
#coding=utf-8
 
def findValues(stringToAnalyse, theSeparators, cleanSpaces = False):
    """
    If stringToAnalyse = "p_1 ; p_2 ; p_3 | r_1 ; r_2 | s"
    and theSeparators = ["|", ";"] then
    the following list will be returned :
 
            [ ['p_1', 'p_2', 'p_3'],
              ['r_1', 'r_2'],
              ['s'] ]
 
    theSeparators must be sorted from the first to find to the last to find.
    """
    if not theSeparators:
        if cleanSpaces:
            stringToAnalyse = stringToAnalyse.strip()
 
        return stringToAnalyse
 
    answer = []
 
    actualSeparator = theSeparators[0]
    remainingSeparators = theSeparators[1:]
 
    piecesOfText = stringToAnalyse.split(actualSeparator)
 
    for onePiece in piecesOfText:
        answer.append( findValues(onePiece, remainingSeparators, cleanSpaces) )
 
    return answer
 
 
################
# LITLLE TESTS #
################
 
if __name__ == '__main__':
    tests = []
 
    tests.append( [ "    p_1    ;  p_2     ;   p_3     |      r_1   ;    r_2     |   s     ", ["|", ";"] ] )
    tests.append( [ "p_1 ; p_2, P-II ; p_3 | r_1 ; r_2 | s", ["|", ";", ","] ] )
    tests.append( [ "p_1 ; p_2, P-II ; p_3", [";"] ] )
 
    for oneTest in tests:
        print '-'*40
        print oneTest[0]
        print findValues(oneTest[0], oneTest[1], cleanSpaces = True)
Je voudrais malgré tout, par simple curiosité, voir comment on pourrait obtenir le même type de fonctionnalité sans utiliser la récursivité. Le nombre de séparateurs est inconnu a priori. Quelqu'un voit-il comment faire ?

Toute info. est la bienvenue.