简体   繁体   中英

Remove n characters from a start of a 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

Yes, just use slices:

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

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

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"

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/

a = 'BarackObama'
a[4:]  # ckObama
b = 'The world is mine'
b[6:]  # rld is mine

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM