Change language

Python | Ways to remove n characters from the beginning of a given string

|

Method # 1: Using the naive method

# Python3 demo code
# how to remove n characters from the beginning
# lines

  
# Initializing string

ini_string1 = ’ garg_akshat’

 
# Initialize the number of characters to remove

n = 5

 
# Print start line

print ( "Initial St ring " , ini_string1)

  
# Remove n characters from the string using
# Naive method

res = ’’

for i in range ( 0 , len (ini_string1)):

if i" = n:

res = res + ini_string 1 [i]

 
# Print the resulting string

print ( "Resultant String" , res)

Output:

 Initial String garg_akshat Resultant String akshat 

Method # 2: Using replace()

# Python3 demo code
# how to remove n characters from the beginning
# lines

  
# Initializing line

ini_string1 = ’garg_akshat’

  
# Initialize the number of characters to remove

n = 5

 
# Print start line

print ( "Initial String" , ini_string1)

 
# Remove n characters from the string using
# replace () function

res = ini_string1.replace (ini_string1 [: 5 ], ’’, 1 )

 
# Print the resulting string 

print ( "Resultant String" , res)

Exit:

 Initial String garg_akshat Resultant String akshat 

Method # 3: Slicing Strings

# Python3 demo code
# how to remove n characters from the beginning
# lines

 
# Initializing line

ini_string1 = ’gargakshat123’

 
# Initialize the number of characters to remove

n = 5

 
# Print start line

print ( "Initial String" , ini_string1)

 
# Remove n characters from the string
# This argument counts the length from zero
# So the length to be removed is skipped n-1

res = ini_string1 [ 4 :]

 
# Print the resulting string

print ( " Resultant String " , res)

  

Exit :

 Initial String gargakshat123 Resultant String akshat123 

Python | Ways to remove n characters from the beginning of a given string Python functions: Questions

Python | Ways to remove n characters from the beginning of a given string String Variables: Questions

Shop

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method