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
.