我有一个字符串 'AAAH8192375948',如何保留这个字符串的前5个字符,并删除其余的部分?是否可以使用带有负整数的 l.strip() 函数?谢谢。
可能的重复问题:
有没有办法在Python中截取字符串?
我有一个字符串 'AAAH8192375948',如何保留这个字符串的前5个字符,并删除其余的部分?是否可以使用带有负整数的 l.strip() 函数?谢谢。
可能的重复问题:
有没有办法在Python中截取字符串?
some_var = 'AAAH8192375948'[:5]
print some_var # AAAH8
[start:end:increment]
-- 如果想使用默认值,数字是可选的(起始位置默认为0,结束位置默认为my_sequence的长度,增量默认为1)。因此: 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
函数可以从字符串的开头和结尾删除一个或多个字符。如果输入一个负数,那么它将尝试删除该负数的字符串表示形式。
>>> # 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')
string[:5]
吗? - thegrinner>>> x = 'AAH8192375948'
>>> x[:5]
'AAH81'
>>> x[:5] + x[5:].strip()
'AAH8192375948'