Python take value of a string after removing part of it

0

What I try to do is put as input value a string where I have to remove the word "name:" and take the first value of the one that follows regardless of whether there is space. example: Entry: Name: Pablo exit- > p

If you could help me I try to learn python and I do not understand chains very well

thanks.

#Este es el código con el que intente
com=0
letra=0
com= raw_input("Entrada:")

if 'nombre:' in com:
    print "encontrado"
    print com.strip("nombre:")
    letra=com.strip("nombre:")
    print letra[0]
else:
    print "no"
    
asked by Pablo Manrique Nieto 04.05.2018 в 18:14
source

2 answers

1

Let's see:

com = 'nombre: pablo'
letra = com.replace('nombre:','').strip()[0])
  • with replace('nombre:','') we replace nombre: with an empty character (we eliminate the word)
  • with strip() we removed the blank spaces if there were
  • And with [0] we cut the first character of the final word
answered by 04.05.2018 / 18:27
source
1

Although the approximation differs from that shown in the question (direct manipulation of the chain itself) another much more flexible way of doing this is through regular expressions. For example:

import re

patt = re.compile(r"\bnombre\b:\s*(\w)")

cad = 'nombre: Pablo'
match = patt.search(cad)
if match:
    print("Primera letra del nombre: {}".format(match.group(1)))
else:
    print("Nombre no encontrado")

In this case the expression is \bnombre\b:\s*(\w) :

  • \bnombre\b - > Search for the word nombre , thanks to \b ( word boundary ) it will not validate "pronoun", "renown", "names", etc.

  • :\s* - > Two points followed by any number of spaces (or none).

  • (\w) - > Group that will contain a single character that can be part of a word.

Some examples of exits:

import re

PATT = re.compile(r"\bnombre\b:\s*(\w)")

def primera_letra_nombre(cadena):
    match = PATT.search(cadena)
    if match:
        return match.group(1)
>>> cad = "nombre: Pablo"
>>> primera_letra_nombre(cad)
'P'
>>> cad = "nombre:      Pablo"
>>> primera_letra_nombre(cad)
'P'
>>> cad = "nombre:Pablo"
>>> primera_letra_nombre(cad)
'P'
>>> cad = "nombre Pablo"
>>> primera_letra_nombre(cad)  # None
>>> cad = "nombre: "
>>> primera_letra_nombre(cad)  # None
>>> cad = "Pablo"
>>> primera_letra_nombre(cad)  # None
>>> cad = "pronombre: él"
>>> primera_letra_nombre(cad)  # None
>>> cad = "appellido: Manrique, nombre: Pablo"
>>> primera_letra_nombre(cad)
'P'
  

With re.search we search only the first match in any part of the chain. If we know that the string always has the substring "name:" (of having it) at the beginning of it, then% co_of% is more efficient. If the string has more than one match and we want to get them all we need to use re.match .

    
answered by 06.05.2018 в 15:25