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
ini_string1 = 'garg_akshat'
n = 5
print("Initial String", ini_string1)
res = ''
for i in range(0, len(ini_string1)):
if i >= n:
res = res + ini_string1[i]
print("Resultant String", res)
Output:
Initial String garg_akshat
Resultant String akshat
Time Complexity: O(n) Auxiliary Space: O(n)
Method #2: Using replace()
Python3
ini_string1 = 'garg_akshat'
n = 5
print("Initial String", ini_string1)
res = ini_string1.replace(ini_string1[:5], '', 1)
print("Resultant String", res)
Output:
Initial String garg_akshat
Resultant String akshat
Time Complexity: O(n) Auxiliary Space: O(n)
Method #3: String slicing
Python3
ini_string1 = 'gargakshat123'
n = 5
print("Initial String", ini_string1)
res = ini_string1[4:]
print("Resultant String", res)
Output:
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)
Time Complexity: O(n), where n is the length of the stringSpace Complexity : O(n)
Last Updated :
24 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Add Your Comment
Please Login to comment...