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
  • 399,953
  • 195
  • 994
  • 1,670
xRobot
  • 25,579
  • 69
  • 184
  • 304
  • 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,601
  • 5
  • 37
  • 55
  • 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
  • 82,968
  • 29
  • 138
  • 152
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
  • 73,987
  • 14
  • 101
  • 130
4
a = 'BarackObama'
a[4:]  # ckObama
b = 'The world is mine'
b[6:]  # rld is mine
Alan Haggai Alavi
  • 72,802
  • 19
  • 102
  • 127