26

Possible Duplicate:
Is there a way to substring a string in Python?

I have a string in the form 'AAAH8192375948'. How do I keep the first 5 characters of this string, and strip all the rest? Is it in the form l.strip with a negative integer? Thanks.

1
  • @user851620 strip() and split() are two distinct functions. Do you really mean strip() ? I wonder what does mean "strip all the rest".
    – eyquem
    Jul 25, 2011 at 16:56

3 Answers 3

45

A string in Python is a sequence type, like a list or a tuple. Simply grab the first 5 characters:

 some_var = 'AAAH8192375948'[:5]
 print some_var # AAAH8

The slice notation is [start:end:increment] -- numbers are optional if you want to use the defaults (start defaults to 0, end to len(my_sequence) and increment to 1). So:

 sequence = [1,2,3,4,5,6,7,8,9,10] # range(1,11)

 sequence[0:5:1] == sequence[0:5] == sequence[:5] 
 # [1, 2, 3, 4, 5]

 sequence[1:len(sequence):1] == sequence[1:len(sequence)] == sequence[1:]
 # [2, 3, 4, 5, 6, 7, 8, 9, 10]

 sequence[0:len(sequence):2] == sequence[:len(sequence):2] == sequence[::2]
 # [1, 3, 5, 7, 9]

strip removes a character or set of characters from the beginning and end of the string - entering a negative number simply means that you are attempting to remove the string representation of that negative number from the string.

1
  • 5
    It is not right: strings are immutable sequence types in Python. Your solution is correct if the value of the slicing is reattributed to the variable, however.
    – brandizzi
    Jul 25, 2011 at 16:24
7

Have you heard about slicing ?

>>> # slice the first 5 characters
>>> first_five = string[:5]
>>>
>>> # strip the rest
>>> stripped = string[5:].strip()
>>>
>>> # in short:
>>> first_five_and_stripped = string[:5], string[5:].strip()
>>>
>>> first_five_and_stripped
('AAAH8', '192375948')
3
  • 1
    Wouldn't it just be string[:5]?
    – thegrinner
    Jul 25, 2011 at 16:20
  • I see what you're doing here but it might be a bit confusing to someone who doesn't yet know about slice notation.
    – senderle
    Jul 25, 2011 at 16:20
  • Quote: How do I keep the first 5 characters of this string, and strip all the rest? @senderle That's why i asked if he have heard of it. But I will complete it
    – Niklas R
    Jul 25, 2011 at 16:21
5

I'm assuming you don't just mean "get rid of everything but the first 5 chars", but rather "keep the first 5 chars and run strip() on the rest".

>>> x = 'AAH8192375948'
>>> x[:5]
'AAH81'
>>> x[:5] + x[5:].strip()
'AAH8192375948'

Not the answer you're looking for? Browse other questions tagged or ask your own question.