2009-04-25 31 views
5

Can you please help me per ottenere le sottostringhe tra i due personaggi ad ogni occorrenzaRicerca di sottostringhe in pitone

Ad esempio per ottenere tutte le stringhe tra "Q" e "E" nel data sequenza esempio in tutte le ricorrenze:

ex: QUWESEADFQDFSAEDFS 

e per trovare la sottostringa con lunghezza minima.

+0

Potresti per favore rivedere la tua domanda e renderla un po 'leggibile, fornendo anche maggiori dettagli? Grazie. – hyperboreean

risposta

16
import re 
DATA = "QUWESEADFQDFSAEDFS" 

# Get all the substrings between Q and E: 
substrings = re.findall(r'Q([^E]+)E', DATA) 
print "Substrings:", substrings 

# Sort by length, then the first one is the shortest: 
substrings.sort(key=lambda s: len(s)) 
print "Shortest substring:", substrings[0] 
7

RichieHindle ha ragione, se non che

substrings.sort(key=len) 

è un modo migliore per esprimere esso che quello lambda ridondante ;-).

Se stai usando Python 2.5 o successivo, min (sottostringa, chiave = len) ti fornirà la stringa più breve (la prima, se più stringhe legano per "il più breve") un po 'più veloce dell'ordinamento e prendendo l'elemento [0] th, ovviamente. Ma se sei bloccato con 2.4 o precedenti, l'approccio di RichieHindle è la migliore alternativa.

+0

Buon punto a proposito della lambda - cosa stavo pensando? 8-) – RichieHindle