2010-04-01 4 views
12

Existe-t-il un moyen de rechercher, à partir d'une chaîne, une ligne contenant une autre chaîne et de récupérer la ligne entière?Rechercher et obtenir une ligne en Python

Par exemple:

string = 
    qwertyuiop 
    asdfghjkl 

    zxcvbnm 
    token qwerty 

    asdfghjklñ 

retrieve_line("token") = "token qwerty" 

Répondre

25

vous avez mentionné "ligne entière", donc je suppose mystring est la ligne.

if "token" in mystring: 
    print mystring 

si vous voulez obtenir juste "azerty jeton",

>>> mystring=""" 
...  qwertyuiop 
...  asdfghjkl 
... 
...  zxcvbnm 
...  token qwerty 
... 
...  asdfghjklñ 
... """ 
>>> for item in mystring.split("\n"): 
... if "token" in item: 
...  print item.strip() 
... 
token qwerty 
3

expressions régulières

import re 
s=""" 
    qwertyuiop 
    asdfghjkl 

    zxcvbnm 
    token qwerty 

    asdfghjklñ 
""" 
>>> items=re.findall("token.*$",s,re.MULTILINE) 
>>> for x in items: 
...  print x 
... 
token qwerty 
15

Si vous préférez une doublure:

matched_lines = [line for line in my_string.split('\n') if "substring" in line] 
+0

je cliqué par erreur sur la bouton "downvote"! Je pense que je dois attendre pour l'upvoting, ou peut-être un edit doit être placé en premier avant que je puisse corriger mon erreur. –

3
items=re.findall("token.*$",s,re.MULTILINE) 
>>> for x in items: 

vous pouvez également obtenir la ligne s'il y a d'autres personnages avant le jeton

items=re.findall("^.*token.*$",s,re.MULTILINE) 

Les travaux ci-dessus comme jeton grep sur unix et mot-clé 'dans' ou .contains en Python et C#

s=''' 
qwertyuiop 
asdfghjkl 

zxcvbnm 
token qwerty 

asdfghjklñ 
''' 

http://pythex.org/ correspond aux 2 lignes suivantes

.... 
.... 
token qwerty 
Questions connexes