Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove n characters from a start of a string

Tags:

python

string

I want to remove the first characters from a string. Is there a function that works like this?

>>> a = "BarackObama"
>>> print myfunction(4,a)
ckObama
>>> b = "The world is mine"
>>> print myfunction(6,b)
rld is mine
like image 431
xRobot Avatar asked May 06 '10 15:05

xRobot


People also ask

How do I remove n characters from a string?

You can use Python's regular expressions to remove the first n characters from a string, using re's . sub() method. This is accomplished by passing in a wildcard character and limiting the substitution to a single substitution.


2 Answers

Yes, just use slices:

 >> a = "BarackObama"
 >> a[4:]
 'ckObama'

Documentation is here http://docs.python.org/tutorial/introduction.html#strings

like image 97
dragoon Avatar answered Oct 02 '22 19:10

dragoon


The function could be:

def cutit(s,n):    
   return s[n:]

and then you call it like this:

name = "MyFullName"

print cutit(name, 2)   # prints "FullName"
like image 36
joaquin Avatar answered Oct 02 '22 18:10

joaquin