Python: Remove last ‘n’ characters of a string

To remove the last ‘n’ characters of a string

'string'[:-n]

or

stringVariable[:-n]

For example, to remove the last character (n=1)

[sai@c7test ~]$ python
Python 2.7.5 (default, Nov 20 2015, 02:00:19)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 'python'[:-1]
'pytho'
>>>
>>> tmpVar = 'Python'
>>> tmpVar[:-1]
'Pytho'
>>>

 

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *