Dada una string y un número ‘n’, la tarea es eliminar una string de longitud ‘n’ del comienzo de la string. Veamos algunos métodos para resolver la tarea dada.
Método n.º 1: uso del método ingenuo
# Python3 code to demonstrate # how to remove 'n' characters from starting # of a string # Initialising string ini_string1 = 'garg_akshat' # Initialising number of characters to be removed n = 5 # Printing initial string print ("Initial String", ini_string1) # Removing n characters from string using # Naive method res = '' for i in range(0, len(ini_string1)): if i>= n: res = res + ini_string1[i] # Printing resultant string print ("Resultant String", res)
Producción:
Initial String garg_akshat Resultant String akshat
Método #2: Usarreplace()
# Python3 code to demonstrate # how to remove 'n' characters from starting # of a string # Initialising string ini_string1 = 'garg_akshat' # Initialising number of characters to be removed n = 5 # Printing initial string print ("Initial String", ini_string1) # Removing n characters from string using # replace() function res = ini_string1.replace(ini_string1[:5], '', 1) # Printing resultant string print ("Resultant String", res)
Producción:
Initial String garg_akshat Resultant String akshat
Método #3: Cortar cuerdas
# Python3 code to demonstrate # how to remove 'n' characters from starting # of a string # Initialising string ini_string1 = 'gargakshat123' # Initialising number of characters to be removed n = 5 # Printing initial string print ("Initial String", ini_string1) # Removing n characters from a string # This argument count length from zero # So length to be stripped is passed n-1 res = ini_string1[4:] # Printing resultant string print ("Resultant String", res)
Producción:
Initial String gargakshat123 Resultant String akshat123
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