2011-06-17 12 views
8
random string 
this is 34 the string 3 that, i need 234 
random string 
random string 
random string 
random string 

random string 
this is 1 the string 34 that, i need 22 
random string 
random string 
random string 
random string 

random string 
this is 35 the string 55 that, i need 12 
random string 
random string 
random string 
random string 

Dentro de una cadena hay varias líneas. Una de las líneas se repite pero con números diferentes cada vez. Me preguntaba cómo puedo almacenar los números en esas líneas. Los números siempre estarán en la misma posición en la línea, pero pueden ser cualquier cantidad de dígitos.¿Cómo agarrar números en el medio de una cadena? (Python)

Editar: Las cadenas aleatorias también podrían tener números en ellas.

+1

use una expresión regular. pydoc re –

Respuesta

7

utilizar expresiones regulares:

>>> import re 
>>> comp_re = re.compile('this is (\d+) the string (\d+) that, i need (\d+)') 
>>> s = """random string 
this is 34 the string 3 that, i need 234 
random string 
random string 
random string 
random string 

random string 
this is 1 the string 34 that, i need 22 
random string 
random string 
random string 
random string 

random string 
this is 35 the string 55 that, i need 12 
random string 
random string 
random string 
random string 
""" 
>>> comp_re.findall(s) 
[('34', '3', '234'), ('1', '34', '22'), ('35', '55', '12')] 
+0

Lo siento, debería haber mencionado esto, pero las otras cadenas aleatorias también podrían tener números en ellas. – Takkun

+0

@Takkun ¿cómo sabes qué líneas te interesan? – OscarRyz

+0

el texto de interés es como ** esto es 35 la cadena 55 que, necesito 12 ** - así que creo que mi expresión regular es la deseada –

4

Mediante el uso de expresiones regulares

import re 
s = """random string 
this is 34 the string 3 that, i need 234 
random string 
random string 
random string 
""" 
re.findall('this is (\d+) the string (\d+) that, i need (\d+)', s)  
4

Suponiendo s está toda la cadena de varias líneas, se puede utilizar un código como

my_list = [] 
for line in s.splitlines(): 
    ints = filter(str.isdigit, line.split()) 
    if ints: 
      my_list.append(map(int, ints)) 

Esta voluntad dale una lista de listas , una lista de enteros para cada línea que contiene enteros. Si prefiere una lista única de todos los números, use

my_list = [int(i) for line in s.splitlines() 
      for i in filter(str.isdigit, line.split())] 
+1

+1 para no usar directamente expresiones regulares –

Cuestiones relacionadas