The problem is that you limit yourself to accessing the characters of the string by index when what, in principle, you want is to iterate over the words.
The simplest way is to use the chain method str.split
and divide the string in a list of substrings using the spaces as a separator. Receive two arguments, the first is a string that is the separator to use and the second argument is an integer that represents the maximum number of partitions we want:
consulta = input('Introduzca situacion laboral:')
consulta = consulta.split()
SL = ['trabajo', 'oficina', 'familia']
print ('La situacion laboral es: ')
print(SL[0], consulta[0])
print(SL[1],consulta[1])
print(SL[2], consulta [2])
Exit:
>>> Introduzca situacion laboral:oficina barrio fernandez
La situacion laboral es:
trabajo oficina
oficina barrio
familia fernandez
If you are going to want to capture phrases you will need to specify a different delimiter. On the other hand, this assumes that the entry is always valid, that it always has three words. If this does not happen you will receive an exception for trying to access a nonexistent index. You can solve this by checking the length of your list returned by split
(asking for the string again or throwing an exception):
sl = ['Trabajo', 'Oficina', 'Familia']
while True:
consulta = input('Introduzca situación laboral: ')
consulta = [sc.strip() for sc in consulta.split(",") if sc.strip()]
if len(consulta) == len(sl):
break
print("Error: Formato de entrada incorrecta.")
print ('La situacion laboral es: ')
print(*("{}: {}.".format(s, c) for s, c in zip(sl, consulta)), sep = "\n")
To pair more complex strings, it may be much simpler to use re.split()
and use regular expressions to determine the pattern:
import re
sl = ['trabajo', 'oficina', 'familia']
patt = re.compile("^\s+|\s*,\s*|\s+$")
while True:
consulta = input('Introduzca situación laboral("Trabajo, Oficina, Familia"): ')
consulta = [sc for sc in re.split(patt, consulta) if sc]
if len(consulta) == len(sl):
break
print("Error: Formato de entrada incorrecta.")
print ('La situacion laboral es: ')
print(*("{}: {}.".format(s, c) for s, c in zip(sl, consulta)), sep = "\n")
For both examples the output is identical, the comma (" ,
") is used as a separator for each item and all spaces that may be at the beginning or at the end of each item are removed:
>>> Introduzca situación laboral: Contable, Barrio La Paz,
Error: Formato de entrada incorrecta.
Introduzca situación laboral: Contable, Barrio La Paz, Fernádez García
La situacion laboral es:
Trabajo: Contable.
Oficina: Barrio La Paz.
Familia: Fernádez García.
Use zip
and cycle for
to print. zip
simply takes two iterables with the same items and creates an iterable with tuples grouping the elements with the same index of each iterable.
Note: It is not necessary to cast%% of the output of str
, in Python 3 input
always return a string.