Python | Ways to remove n characters from start of given string
Given a string and a number ‘n’, the task is to remove a string of length ‘n’ from the start of the string. Let’s a few methods to solve the given task.
Method #1: Using Naive Method
Python3
# 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) |
Initial String garg_akshat Resultant String akshat
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2: Using replace()
Python3
# 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) |
Initial String garg_akshat Resultant String akshat
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3: String slicing
Python3
# 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) |
Initial String gargakshat123 Resultant String akshat123
Time Complexity: O(n)
Auxiliary Space: O(n)
Using the join() method and a list comprehension:
Approach:
In this example, we have a string variable containing the original string and an n variable containing the number of characters we want to remove from the start of the string. We pass these variables as arguments to the remove_n_chars_from_start() function and store the result in the new_string variable. Finally, we print the new_string variable to see the resulting string after removing n characters from the start.
Python3
def remove_n_chars_from_start(string, n): return ''.join([string[i] for i in range (n, len (string))]) string = "hello world" n = 3 new_string = remove_n_chars_from_start(string, n) print (new_string) # Output: "lo world" |
lo world
Time Complexity: O(n), where n is the length of the string
Space Complexity: O(n)
Contact Us