2014-04-08 1 views
5

C'è un modo per tagliare una stringa per iniziare e terminare in punti specifici?Come tagliare una stringa: iniziare immediatamente dopo il primo stop completo e terminare all'ultimo

Ecco un esempio: Vorrei che la stringa (testo) inizi immediatamente dopo il primo arresto completo e termini all'ultimo arresto completo.

_string = "money is good. love is better. be lucky to have any. can't really have both" 

uscita prevista:

"love is better. be lucky to have any." 

Il mio tentativo:

import re 
pattern = "\.(?P<_string>.*?.*?).\" 
match = re.search(pattern, _string) 
if match != None: 
    print match.group("_string") 

Il mio tentativo è partito bene ma si fermò al secondo full_stop.

Qualche idea su come arrivare all'output atteso?

risposta

5

Questo funzionerà, se nella stringa c'è almeno un punto.

print _string[_string.index(".") + 1:_string.rindex(".") + 1] 
# love is better. be lucky to have any. 

Se non si desidera che lo spazio all'inizio, poi si striscia che come questo

print _string[_string.index(".") + 1:_string.rindex(".") + 1].lstrip() 
# love is better. be lucky to have any. 
+0

nice one fratello. Grazie molto,. – Tiger1

+0

@ Tiger1 Sono contento di essere stato di aiuto :) Bene, conosci il trapano. Per favore considera di accettare questa risposta se ti aiuta;) – thefourtheye

+0

La divisione è più veloce. –

0

La regex dovrebbe essere:

\.(.*\.) 

questo si prenderà tutto il testo tranne newline tra il primo e l'ultimo .

spiegazione:

\. matches the character . literally 
1st Capturing group (.*\.) 
    .* matches any character (except newline) 
     Quantifier: Between zero and unlimited times, as many times as possible, giving back as needed [greedy] 
    \. matches the character . literally 

se non si desidera che lo spazio all'inizio basta usare questo:

\.\s(.*\.) 

speranza che questo aiuti.

1

Che dire dell'utilizzo dei metodi .index() e .rindex() con l'affettamento delle stringhe?

string = "money is good. love is better. be lucky to have any. can't really have both" 
first_full_stop = string.index('.') 
last_full_stop = string.rindex('.') 
string = string[first_full_stop+1:last_full_stop+1] 

Oppure si può dividere da punti (questo funziona con qualsiasi numero di punti fermi):

string = "money is good. love is better. be lucky to have any. can't really have both" 
string = string.split('.') 
string = string[1:-1] 
2
import re 
_string = "money is good. love is better. be lucky to have any. can't really have both" 
str1 =_string[_string.find(".")+1:] 
for i in range(len(str1)-1,0,-1): 
if(str1[i]=='.'): 
    a=str1[:i+1] 
    break 
print a 
#love is better. be lucky to have any.