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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output:

Initial String garg_akshat
Resultant String akshat

 
Method #2: Using replace()

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output:

Initial String garg_akshat
Resultant String akshat

 
Method #3: String slicing

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)
     

chevron_right


Output:

Initial String gargakshat123
Resultant String akshat123


My Personal Notes arrow_drop_up

Programming freaktech Enthusiast and have interest in learning new upcoming technologies

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.