Strip all but first 5 characters

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.


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.


我假设你不仅仅是指“除了前5个字符之外的所有东西”,而是“保留前5个字符并在其余部分运行strip()”。

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

你有没有听说过切片?

>>> # 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')
链接地址: http://www.djcxy.com/p/55110.html

上一篇: 我怎样才能删除python中的字符串的最后一个字符?

下一篇: 除前5个字符外的所有字符