17

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
jfs
  • 374,366
  • 172
  • 933
  • 1,594
xRobot
  • 24,150
  • 62
  • 173
  • 291
  • 11
    I have never written a word of Python and yet I was able to find the answer to this. I suggest you search for "String Manipulation in Python" in Google. Here's one link: http://www.astro.ufl.edu/~warner/prog/python.html – Armstrongest May 06 '10 at 15:42
  • possible duplicate of [how to remove left part of a string in python?](http://stackoverflow.com/questions/599953/how-to-remove-left-part-of-a-string-in-python) – outis Apr 19 '12 at 22:31

4 Answers4

18

Yes, just use slices:

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

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

dragoon
  • 5,260
  • 5
  • 35
  • 53
  • 3
    Short, succinct and clear. With a reference directly to String section. Mine is just a poor rehash. I learned some Python to answer this question... and I shall now remove my answer. Must cut the clutter! – Armstrongest May 06 '10 at 15:41
13

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"
joaquin
  • 78,380
  • 27
  • 136
  • 151
8

Use slicing.

>>> a = "BarackObama"
>>> a[4:]
'ckObama'
>>> b = "The world is mine"
>>> b[6:10]
'rld '
>>> b[:9]
'The world'
>>> b[:3]
'The'
>>>b[:-3]
'The world is m'

You can read about this and most other language features in the official tutorial: http://docs.python.org/tut/

Community
  • 1
  • 1
Mike Graham
  • 69,495
  • 14
  • 96
  • 129
4
a = 'BarackObama'
a[4:]  # ckObama
b = 'The world is mine'
b[6:]  # rld is mine
Alan Haggai Alavi
  • 69,934
  • 19
  • 98
  • 125