Dada una string y un carácter, su tarea es encontrar la primera posición del carácter en la string. Estos tipos de problemas son una programación muy competitiva en la que necesita ubicar la posición del carácter en una string.
Analicemos algunos métodos para resolver el problema.
Método n.º 1: uso del método ingenuo
Python3
# Python3 code to demonstrate # to find the first position of the character # in a given string # Initializing string ini_string = 'abcdef' # Character to find c = "b" # printing initial string and character print ("initial_string : ", ini_string, "\ncharacter_to_find : ", c) # Using Naive Method res = None for i in range(0, len(ini_string)): if ini_string[i] == c: res = i + 1 break if res == None: print ("No such character available in string") else: print ("Character {} is present at {}".format(c, str(res)))
Producción:
initial_string : abcdef character_to_find : b Character b is present at 2
Método n.º 2: usar find
Este método devuelve -1 en caso de que el carácter no esté presente.
Python3
# Python3 code to demonstrate # to find first position of character # in a given string # Initializing string ini_string = 'abcdef' ini_string2 = 'xyze' # Character to find c = "b" # printing initial string and character print ("initial_strings : ", ini_string, " ", ini_string2, "\ncharacter_to_find : ", c) # Using find Method res1 = ini_string.find(c) res2 = ini_string2.find(c) if res1 == -1: print ("No such character available in string {}".format( ini_string)) else: print ("Character {} in string {} is present at {}".format( c, ini_string, str(res1 + 1))) if res2 == -1: print ("No such character available in string {}".format( ini_string2)) else: print ("Character {} in string {} is present at {}".format( c, ini_string2, str(res2 + 1)))
Producción:
initial_strings : abcdef xyze character_to_find : b Character b in string abcdef is present at 2 No such character available in string xyze
Método n.º 3: uso de index()
Este método genera un error de valor en caso de que el carácter no esté presente
Python3
# Python3 code to demonstrate # to find first position of character # in a given string # Initializing string ini_string1 = 'xyze' # Character to find c = "b" # printing initial string and character print ("initial_strings : ", ini_string1, "\ncharacter_to_find : ", c) # Using index Method try: res = ini_string1.index(c) print ("Character {} in string {} is present at {}".format( c, ini_string1, str(res + 1))) except ValueError as e: print ("No such character available in string {}".format(ini_string1))
Producción:
initial_strings : xyze character_to_find : b No such character available in string xyze
Publicación traducida automáticamente
Artículo escrito por garg_ak0109 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA